c# - 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 来转换文件。
解决方案
推荐阅读
- angular - Angular 8分页pageCount不更新
- sql-server - 如何同时管理 Always Encrypted 技术和 TDE 并降低风险?
- redis - Redis 流 50k 消费者支持并行 - 容量要求
- java - 如何自动从 Firebase 中删除?
- algorithm - 为什么渐近复杂性类比不起作用?
- python-3.x - 包裹在函数中时 Python 代码变慢
- c# - 如何在 ASP.NET Core 中路由以删除错误 404 Not found
- string - 如何知道这个文件的编码?
- elixir - 如何通过 Ecto Multi 从先前插入的表键中检索 id
- ios - 如何从标签栏控制器更改标签栏项目