我尝试结合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.
;
结束时才会终止。在PowerShell中,不需要显式语句终止符,你可以在某些情况下不使用行尾反斜杠,特别是当语句明显不完整时,尤其是在行尾|
之后,类似于上面的ps
示例:行尾.
- 也就是说,。
必须在行末,PowerShell才知道该语句是否继续。 - mklement0|
来继续管道。也就是说,虽然Windows PowerShell仅支持例如Get-Date |<newline> Format-List
,而 PowerShell(Core) 7+ 现在也支持Get-Date<newline>| Format-List
,尽管仅限于脚本,因为交互式地执行Get-Date
语句时,在你有机会继续语句之前它会先被执行(除了在{ ... }
中)。 - mklement0