我正在尝试在我的应用程序中使用 c# 编写一个 powershell 脚本。问题是,如果我使用 C# 运行该脚本,它就无法完成工作,但如果我手动运行它,它就可以完成工作。
这是脚本:DISM/online/Enable-Feature/Featurename:NetFx3/All
该脚本在 Windows 服务器上启用 Framwork 3.5。 Source
我的代码:
NuGet: System.Management.Automation
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("DISM /online /Enable-Feature /Featurename:NetFx3 /All ");
// begin invoke execution on the pipeline
IAsyncResult result = PowerShellInstance.BeginInvoke();
// do something else until execution has completed.
// this could be sleep/wait, or perhaps some other work
while (result.IsCompleted == false)
{
Console.WriteLine("Waiting for pipeline to finish...");
Thread.Sleep(1000);
// might want to place a timeout here...
}
Console.WriteLine("Finished!");
}
我使用了 Here 中的示例
注意:我的应用以管理员身份运行。
最佳答案
尝试将管理员权限添加到您的 powershell 脚本中,有时这会有所帮助
PowerShell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -windowstyle hidden -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -noexit -File "$ScriptPath"' -Verb RunAs}"
您可以将 powershell 命令保存在 ps1 文件中,并将路径作为参数 ($ScriptPath)。此 powershell 命令已通过运行您指定的代码在 C# 上进行测试。希望这可以帮助。如果不是,那么我建议使用 C# System.Diagnostics 命名空间中的 Process。
关于c# - 从 c# 运行 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49717621/