尝试使用powershell运行远程命令,但运气不佳
我正在寻找帮助,以便在远程计算机上运行有关mcafee代理线路的命令,以便远程运行it命令尝试使用powershell运行远程命令,但运气不佳,powershell,automation,scripting,Powershell,Automation,Scripting,我正在寻找帮助,以便在远程计算机上运行有关mcafee代理线路的命令,以便远程运行it命令 $Machines = Get-Content -Path "C:\server_list.txt" foreach ($computer in $Machines){ Write-host "Executing Events on $computer" -b "yellow" -foregroundcolor "red" $command = Start-Process -NoNewWindow
$Machines = Get-Content -Path "C:\server_list.txt"
foreach ($computer in $Machines){
Write-host "Executing Events on $computer" -b "yellow" -foregroundcolor "red"
$command = Start-Process -NoNewWindow -FilePath "C:\Program Files\McAfee\Agent\cmdagent.exe" -ArgumentList "/e /l C:\temp"
Invoke-Command -ComputerName $computer -ScriptBlock {$command}
}
当我执行这个命令时,在本地运行,而不是远程运行
$Machines = Get-Content -Path "C:\server_list.txt"
foreach ($computer in $Machines){
Write-host "Executing Events on $computer" -b "yellow" -foregroundcolor "red"
$command = Start-Process -NoNewWindow -FilePath "C:\Program Files\McAfee\Agent\cmdagent.exe" -ArgumentList "/e /l C:\temp"
Invoke-Command -ComputerName $computer -ScriptBlock {$command}
}
我在这里寻求帮助,我没有完全的经验,但我开始在我的工作中自动化一些任务
请提出一些建议
我真的很感激
谢谢
$command=Start Process-nonewindow-FilePath“C:\Program Files\McAfee\Agent\cmdagent.exe”-ArgumentList”/e/l C:\temp“
这并没有为以后使用Invoke command
执行定义命令,它会立即执行Start Process
命令,这不是您的意图,也是它在本地运行的原因
要解决这个问题,您必须将其定义为脚本块({…}
):$command={Start Proces…}
,然后按原样将其传递给调用command
的-ScriptBlock
参数(调用命令-ComputerName$computer-ScriptBlock$command
)(不要再次将其括在{…}
中)
此外,我建议利用Invoke命令
的能力,一次并行地将多台计算机作为目标,并避免使用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命令中定义脚本块
调用:
Invoke-Command -ComputerName $machines -ScriptBlock {
& "C:\Program Files\McAfee\Agent\cmdagent.exe" /e /l C:\temp
}
以远程计算机为目标时,一个值得注意的缺陷是不能直接引用(远程执行)脚本块中的局部变量,而必须通过
$using:
作用域显式引用它们;e、 例如,$using:someLocalVar
而不是$someLocalVar
-有关详细信息,请参阅。问题是$command
仅对本地会话有效-如果您尝试在远程会话中使用它,$command
为$null
,并且不执行任何操作。此外,您实际上是在分配$command
任何启动进程
返回的内容,而不是您想要的命令
只需将该命令放在脚本块中(在执行该命令时,您可以在每台机器上使用单个命令运行该命令,而无需同步循环):