如何在不同的进程中运行 PowerShell 脚本并向其传递参数?

lix*_*onn 5 windows powershell process

假设我有一个脚本:

write-host "Message.Status: Test Message Status";
Run Code Online (Sandbox Code Playgroud)

我设法通过执行以下操作在单独的进程中运行它:

powershell.exe -Command
{ write-host "Message.Status: Test Message Status"; }  
Run Code Online (Sandbox Code Playgroud)

问题是我想将参数传递给脚本,以便我可以实现如下目标:

write-host "I am in main process"
powershell.exe -Command -ArgumentList "I","am","here"
{
    write-host "I am in another process"
    write-host "Message.Status: $($one) $($two) $($three)";
}
Run Code Online (Sandbox Code Playgroud)

但是-ArgumentList在这里不起作用

我得到:

powershell.exe : -ArgumentList : The term '-ArgumentList' is not recognized as the name of a cmdlet, function, script file, or operable 
Run Code Online (Sandbox Code Playgroud)

我需要在不同的进程中运行 PowerShell 脚本文件的某些部分,并且由于 PowerShell 脚本已上传到外部系统,因此我无法使用另一个文件。

Mar*_*ndl 5

-Command参数需要一个,scriptblock您可以在其中使用块定义参数Param()。然后使用-args参数传入参数。-args您唯一的错误是将after放在定义脚本块-command 之前。

这就是它的工作原理:

write-host "I am in main process $($pid)"
powershell.exe -Command {
    Param(
        $one,
        $two,
        $three
    )
    write-host "I am in process $($pid)"
    write-host "Message.Status: $($one) $($two) $($three)";
} -args "I", "am", "here" | Out-Null
Run Code Online (Sandbox Code Playgroud)

输出:

I am in main process 17900
I am in process 10284
Message.Status: I am here
Run Code Online (Sandbox Code Playgroud)