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

How to execute a powershell script using c# and setting execution policy?

我试图结合两个来自 Whosebug 的答案 (first & )

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

在我的 powershell 脚本中,我有以下参数:

Param(
[String]$key
)

但是,当我执行此操作时,出现以下异常:

System.Management.Automation.CmdletInvocationException: Cannot validate argument on parameter 'Session'. 
The argument is null or empty. 
Provide an argument that is not null or empty, and then try the command again.

在不知道您的具体问题是什么的情况下,请注意,您的 C# 代码可以大大简化,这也可能解决您的问题:

  • 无需诉诸反射来设置会话的执行策略。

  • 使用 PowerShell class 的实例大大简化了命令调用。

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

注意:如果在执行 PowerShell 脚本期间发生 终止 错误,.Invoke() 方法只会抛出异常。更典型的 非终止 错误改为通过 .Streams.Error.

报告