我试图结合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.