[英]How to execute a powershell script using c# and setting execution policy?
我試圖結合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();
在不知道您的具體問題是什么的情況下,請注意您的 C# 代碼可以大大簡化,這也可以解決您的問題:
無需借助反射<\/em>來設置會話的執行策略。
使用
PowerShell<\/code><\/a>類的實例極大地簡化了命令調用。
注意:
.Invoke()<\/code>方法僅在 PowerShell 腳本執行期間發生終止<\/em>錯誤時才會引發異常。
更典型的非終止<\/em>錯誤通過
.Streams.Error<\/code>報告。
"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.