简体   繁体   English

从C#运行Powershell

[英]Run Powershell from C#

I need to start a powershell script from C# and get the PSSSecurityException on pipeline.Invoke() 我需要从C#启动Powershell脚本,并在Pipeline.Invoke()上获取PSSSecurityException。

AuthorizationManager check failed. AuthorizationManager检查失败。

My code: 我的代码:

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();
}

Questions 问题

  1. I suspect that I need to set PSCredential. 我怀疑我需要设置PSCredential。 But I can not promt for it, so I have to handle this in code. 但是我无法对此进行提示,因此我必须在代码中进行处理。 Can this be done in a secure way? 可以安全的方式进行吗? ( This was not the case ) 不是这种情况

Check out this SuperUser post: https://superuser.com/questions/106360/how-to-enable-execution-of-powershell-scripts 查看此SuperUser帖子: https : //superuser.com/questions/106360/how-to-enable-execution-of-powershell-scripts

You probably just need to allow unsigned scripts to run. 您可能只需要允许运行未签名的脚本即可。 In the PS console, type the following: 在PS控制台中,键入以下内容:

set-executionpolicy remotesigned

Another resource echoes this: http://tgnp.me/2011/09/powershell-authorizationmanager-check-failed-resolution/ 另一个资源也与此相呼应: http : //tgnp.me/2011/09/powershell-authorizationmanager-check-failed-resolution/

Give that a try and let me know what happens. 试试看,让我知道会发生什么。

To capture the output from the script, try this: 要捕获脚本的输出,请尝试以下操作:

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>
}

The problem was that the script was placed on a share. 问题在于该脚本已放置在共享上。 To run scripts on this share I needed to add the share to Trusted Sites. 要在此共享上运行脚本,我需要将该共享添加到“受信任的站点”。

在此处输入图片说明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM