Run Powershell from C#

醉酒当歌 提交于 2019-12-11 03:59:10

问题


I need to start a powershell script from C# and get the PSSSecurityException on pipeline.Invoke()

AuthorizationManager check failed.

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. 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)

回答1:


Check out this SuperUser post: 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:

set-executionpolicy remotesigned

Another resource echoes this: 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>
}



回答2:


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.



来源:https://stackoverflow.com/questions/21855037/run-powershell-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!