【问题标题】:Trying to run commands remote with powershell but not luck尝试使用 powershell 远程运行命令但不走运
【发布时间】:2020-03-29 13:52:10
【问题描述】:

我正在寻求帮助,以便在远程计算机上运行有关 mcafee 代理线的命令以使其命令远程运行。

$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}
}

当我执行这个命令时,在本地而不是远程运行。

我在这里寻求帮助我没有完全的经验,但我已经开始在我的工作中自动完成一些任务。

请提出一些建议

非常感谢

谢谢

【问题讨论】:

    标签: powershell automation scripting


    【解决方案1】:

    $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 了解更多信息。

    【讨论】:

      【解决方案2】:

      问题是$command 仅对您的本地会话有效 - 如果您尝试在远程会话中使用它,$command$null 并且什么都不做。此外,您实际上是在分配 $command 无论 Start-Process 返回什么,而不是您想要的命令。

      只需将命令放在脚本块中(当您使用它时,您可以使用单个命令在每台机器上运行此命令,而无需同步遍历每个命令):

      Invoke-Command -ComputerName $Machines -ScriptBlock { Start-Process -NoNewWindow -FilePath "C:\Program Files\McAfee\Agent\cmdagent.exe" -ArgumentList "/e /l C:\temp" }
      

      【讨论】:

        猜你喜欢
        • 2018-05-27
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 2012-04-28
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多