从C#运行Powershell

时间:2014-02-18 13:17:27

标签: c# powershell runspace

我需要从C#启动一个powershell脚本,并在pipeline.Invoke()

上获取PSSSecurityException。
  

AuthorizationManager检查失败。

我的代码:

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptfile);
    pipeline.Commands.Add(scriptCommand);
    pipeline.Invoke();
}

问题

  1. 我怀疑我需要设置PSCredential。但我无法承诺,所以我必须在代码中处理这个问题。这可以以安全的方式完成吗? (情况并非如此

2 个答案:

答案 0 :(得分:2)

查看此超级用户帖子:https://superuser.com/questions/106360/how-to-enable-execution-of-powershell-scripts

您可能只需要允许运行未签名的脚本。在PS控制台中,键入以下内容:

set-executionpolicy remotesigned

另一个资源回应:http://tgnp.me/2011/09/powershell-authorizationmanager-check-failed-resolution/

尝试一下,让我知道会发生什么。

要捕获脚本的输出,请尝试以下操作:

Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
    <here you can ToString the psObject for the output and write it line by line to your log>
}

答案 1 :(得分:1)

问题是该脚本被放置在共享上。要在此共享上运行脚本,我需要将共享添加到可信站点。

enter image description here

enter image description here