首页 > 解决方案 > C# Powershell 代码未在 Windows 7 上执行

问题描述

通过我的 C# 应用程序执行的 Powershell 代码在 Windows 10 上完美执行,但甚至无法在 Windows 7 上运行。它也没有超出 Process.WaitForExit()

我尝试在代码中使用 Powershell (System.Management.Automation) 本身。我还设置了“set-executionpolicy remotesigned”,它使用 powershell 脚本 (.ps1) 运行,但在我的 C# 代码中使用它时不运行,如下所示。

        Process p = new Process();
        p.StartInfo.FileName = "powershell";
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = true;
        p.Start();

        using (StreamWriter sw = p.StandardInput)
        {
            if (sw.BaseStream.CanWrite)
            {
                string pdfName = fileName.Substring(0, fileName.Length - new FileInfo(fileName).Extension.Length) + ".pdf";

                sw.WriteLine("$Exl = New-Object -ComObject Excel.Application");
                sw.WriteLine("$Doc = $Exl.Workbooks.Open(\"" + fileName + "\")");
                sw.WriteLine("$Doc.ExportAsFixedFormat([Microsoft.Office.Interop.Excel.XlFixedFormatType]::xlTypePDF, \"" + pdfName +"\")");
                sw.WriteLine("$Doc.Close($False)");
                sw.WriteLine("[gc]::Collect()");
                sw.WriteLine("[gc]::WaitForPendingFinalizers()");
                sw.WriteLine("$Exl.Quit()");
                sw.WriteLine("[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Exl)");
                sw.WriteLine("Remove-Variable Exl");
            }
        }
        p.WaitForExit();

在 Windows 10 上,该脚本成功地将 Excel 文件转换为 pdf,但在 Windows 7 上 - 该脚本甚至没有打开 Excel 来转换文件。

标签: c#powershell

解决方案


推荐阅读