从 C# 运行 powershell 脚本

Bad*_*Ass 6 c# powershell

我正在尝试在我的应用程序中使用 c# 编写一个 powershell 脚本。问题是,如果我用 c# 运行脚本,它就不能工作,但如果我手动运行它,它就可以工作。

那是脚本: DISM /online /Enable-Feature /Featurename:NetFx3 /All

该脚本在 Windows 服务器上启用框架 3.5。来源

我的代码:

纽格: 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!");
}
Run Code Online (Sandbox Code Playgroud)

我使用了这里的例子

注意:我的应用程序以管理员身份运行。

小智 3

尝试将管理员权限添加到您的 powershell 脚本中,有时这会有所帮助

PowerShell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -windowstyle hidden -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -noexit -File "$ScriptPath"' -Verb RunAs}"
Run Code Online (Sandbox Code Playgroud)

您可以将 powershell 命令保存在 ps1 文件中,并将路径作为参数 ($ScriptPath)。此 powershell 命令通过运行您指定的代码在 C# 上进行测试。希望这可以帮助。如果没有,那么我建议使用 C# System.Diagnostics 命名空间中的 Process。