$command = Start-Process -NoNewWindow -FilePath "C:\Program Files\McAfee\Agent\cmdagent.exe" -ArgumentList "/e /l C:\temp"
这并没有用Invoke-Command 定义一个命令供以后执行,它立即执行Start-Process 命令,这不是你的意图,它是它在本地运行的原因。
要解决这个问题,您必须将它定义为脚本块 ({ ... }):
$command = { Start-Proces ... },然后按原样传递它 em> 到Invoke-Command 的-ScriptBlock 参数(Invoke-Command -ComputerName $computer -ScriptBlock $command)(不要将它包含在{ ... } 中再次)。
此外,我建议利用Invoke-Command 的能力同时并行地定位多台 计算机,并避免使用Start-Process 同步调用同一外部程序窗口。
把它们放在一起:
$machines = Get-Content -Path "C:\server_list.txt"
Write-host "Executing Events on the following computers: $machines" -b "yellow" -foregroundcolor "red"
# Define the command as a script block, which is a piece of PowerShell code
# you can execute on demand later.
# In it, execute cmdagent.exe *directly*, not via Start-Process.
$command = { & "C:\Program Files\McAfee\Agent\cmdagent.exe" /e /l C:\temp }
# Invoke the script block on *all* computers in parallel, with a single
# Invoke-Command call.
Invoke-Command -ComputerName $machines -ScriptBlock $command
注意需要使用调用运算符& 来调用cmdagent.exe 可执行文件,因为它的路径被引用(由于包含空格,这是必要的)。
或者,您可以直接在Invoke-Command 调用中定义脚本块:
Invoke-Command -ComputerName $machines -ScriptBlock {
& "C:\Program Files\McAfee\Agent\cmdagent.exe" /e /l C:\temp
}
针对远程计算机的一个显着缺陷是您不能直接引用(远程执行)脚本块中的本地变量,而必须通过$using: 范围显式引用它们;例如,$using:someLocalVar 而不是 $someLocalVar - 请参阅 this answer 了解更多信息。