2

我试图结合stackoverflow的两个答案(第一个第二个

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

1 回答 1

3

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

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

  • 使用PowerShell类的实例极大地简化了命令调用。

// 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

于 2021-08-26T17:01:14.520 回答