[英]How to execute a powershell script using c# and setting execution policy?
I tried to combine two answers from stackoverflow ( first<\/a> & second<\/a> )我试图结合stackoverflow的两个答案( 第一个<\/a>和第二个<\/a>)
InitialSessionState iss = InitialSessionState.CreateDefault();
// Override ExecutionPolicy
PropertyInfo execPolProp = iss.GetType().GetProperty(@"ExecutionPolicy");
if (execPolProp != null && execPolProp.CanWrite)
{
execPolProp.SetValue(iss, ExecutionPolicy.Bypass, null);
}
Runspace runspace = RunspaceFactory.CreateRunspace(iss);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
results = pipeline.Invoke();
Without knowing what your specific problem was, note that your C# code can be greatly streamlined, which may also resolve your problem:在不知道您的具体问题是什么的情况下,请注意您的 C# 代码可以大大简化,这也可以解决您的问题:
There is no need to resort to reflection<\/em> in order to set a session's execution policy.无需借助反射<\/em>来设置会话的执行策略。
<\/li> Using an instance of the PowerShell<\/code><\/a> class greatly simplifies command invocation.
使用
PowerShell<\/code><\/a>类的实例极大地简化了命令调用。
<\/li><\/ul>
\/\/ Create an initial default session state. var iss = InitialSessionState.CreateDefault2(); \/\/ Set its script-file execution policy (for the current session only). iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass; \/\/ Create a PowerShell instance with a runspace based on the \/\/ initial session state. PowerShell ps = PowerShell.Create(iss); \/\/ Add the command (script-file call) and its parameters, then invoke. var results = ps .AddCommand(scriptfile) .AddParameter("key", "value") .Invoke();<\/code><\/pre> Note: The .Invoke()<\/code> method only throws an exception if a terminating<\/em> error occurred during execution of the PowerShell script.
注意: .Invoke()<\/code>方法仅在 PowerShell 脚本执行期间发生终止<\/em>错误时才会引发异常。
The more typical non-terminating<\/em> errors are instead reported via .Streams.Error<\/code> .
更典型的非终止<\/em>错误通过.Streams.Error<\/code>报告。
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.