简体   繁体   English

"如何使用 c# 执行 powershell 脚本并设置执行策略?"

[英]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# 代码可以大大简化,这也可以解决您的问题:

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

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