我试着从stackoverflow (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
类的实例大大简化了命令调用。
// 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();
注意:.Invoke()
方法只在执行PowerShell脚本时发生终止错误时抛出异常。更典型的非终止错误是通过.Streams.Error
报告的。