【问题标题】:Starting PowerShell Script with Process.Start closes PowerShell with no error使用 Process.Start 启动 PowerShell 脚本会关闭 PowerShell 且没有错误
【发布时间】:2021-05-24 15:34:42
【问题描述】:

我正在用 C# 编写一个小应用程序,它调用各种 PowerShell 脚本来配置计算机。

我现在遇到了一个问题,我认为我上次处理它时只是几周前。

当我从 C# 调用这些脚本时,PowerShell 窗口会非常短暂地打开然后关闭。我以为我的 PS 脚本可能有错误,但是没有——如果我在开始时执行 Start-Transcript,我仍然没有得到任何输出,所以它显然甚至没有开始运行我的脚本。

我的代码:

Process.Start(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe ", @"C:\Thunder\Scripts\3-BitLockerEnable.ps1");

我认为执行策略可能是问题所在,但它设置为不受限制。我确保文件路径是正确的 - 只需删除 PowerShell 调用即可让我检查,它会在没有该行的情况下在记事本中打开 ps1 文件。

感谢任何帮助,我不确定我在哪里犯了错误。我可以发誓这个确切的代码在几周前运行良好。谢谢。

【问题讨论】:

    标签: c# powershell windows-10 execution


    【解决方案1】:

    使用内置的 PowerShell 对象:

    PowerShell ps = PowerShell.Create();
    ps.AddScript(File.ReadAllText(@"C:\Thunder\Scripts\3-BitLockerEnable.ps1")).Invoke();
    

    【讨论】:

    • 按照您的建议运行它会给出:PSSnapInException: System error. System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadMshSnapinAssembly (System.Management.Automation.PSSnapInInfo mshsnapinInfo) (at <a866df73fe6e416dad3eec8d3078bb68>:0) 和几行。非常普遍的错误,所以我不确定那里发生了什么。
    • 我正在使用 System.Management.Automation 和 Microsoft.PowerShell 和 Microsoft.Powershell.Commands,不知道具体是哪一个或是否需要其他任何东西才能使其工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 2019-06-16
    相关资源
    最近更新 更多