c# - 从 c# 运行 powershell 脚本

标签 c# powershell

我正在尝试在我的应用程序中使用 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/

相关文章:

c#httpwebrequest凭证问题

c# - 中继器内的 DropDownList : How to handle SelectedIndexChange and get DataItem?

c# - 如何进行 ASP.NET 依赖注入(inject)

arrays - PowerShell-在forEach循环中未创建锯齿状数组

debugging - 无法通过 Visual Studio 调试 PowerShell

powershell - 将多行中的2行复制到新文件中

c# - MongoDB 在正则表达式查询中使用索引

c# - Windows 窗体的 MVP 示例

.net - 在 64 位环境中使用 32 位 COM 对象

powershell - 如何将颜色线插入 StringBuilder 对象