代码之家  ›  专栏  ›  技术社区  ›  Mike Bruno

powershell-从远程计算机上运行exe的invoke命令捕获输出

  •  2
  • Mike Bruno  · 技术社区  · 7 年前

    我尝试了显而易见的方法(将invoke命令的结果分配给字符串):

    > $command =  "Start-Process -FilePath `"auditpol.exe`" -ArgumentList `"/set`", `"/subcategory`", `"```"File System```"`", `"/success:enable`""
    > $command
    "auditpol.exe" -ArgumentList "/set", "/subcategory", "`"File System`"", "/success:enable"
    
    > $out = Invoke-Command -ComputerName MyServer -ScriptBlock {$command}
    > $out
    >
    

    但是$out是空的。

    我还尝试了 this MSDN blog 使用等待作业和接收作业。结果有些许希望,但没有定论:

    > $command =  "Start-Process -FilePath `"auditpol.exe`" -ArgumentList `"/set`", `"/subcategory`", `"```"File System```"`", `"/success:enable`""
    > $command
    "auditpol.exe" -ArgumentList "/set", "/subcategory", "`"File System`"", "/success:enable"
    > $job = Invoke-Command -ComputerName MyServer -ScriptBlock {$command} -AsJob
    > Wait-Job $job
    
    Id              Name            State      HasMoreData     Location             Command                  
    --              ----            -----      -----------     --------             -------                  
    3               Job3            Completed  True            MyServer  $command
    
    > $output = Receive-Job $job
    > $output
    >
    

    我确实从等待工作中得到了一些信息。根据 Microsoft documentation of Wait-Job 状态=已完成

    1 回复  |  直到 7 年前
        1
  •  3
  •   mklement0    7 年前

    运行控制台程序 同步地 它的stdout和stderr输出可用于捕获 调用它 直接地 -不使用 Start-Process (无论您在本地还是远程运行该程序,通过 Invoke-Command )以下内容:

    $out = Invoke-Command -ComputerName MyServer -ScriptBlock {
      auditpol.exe /set /subcategory 'File System' /success:enable
    }
    

    如果你还想抓住 标准错误 输出,附加 2>&1 auditpol.exe 打电话来。


    如果脚本块存储在局部变量中 $command (作为 [scriptblock] 实例,而不是 一串 ),直接传递给 -ScriptBlock 以下内容:

    # Create a script block (a piece of code that can be executed on demand later)
    # and store it in a (local) variable.
    # Note that if you were to use any variable references inside the block,
    # they would refer to variables on the remote machine if the block were to be
    # executed remotely.
    $command = { auditpol.exe /set /subcategory 'File System' /success:enable }
    
    # Pass the script block to Invoke-Command for remote execution.
    $out = Invoke-Command -ComputerName MyServer -ScriptBlock $command
    

    至于 你所尝试的 以下内容:

    $out = Invoke-Command -ComputerName MyServer -ScriptBlock {$command}
    

    您正在传递一个脚本块文本( { ... } )当它在目标计算机上执行时,引用一个名为 .

    通常,只是引用一个变量 输出其值 执行

    更重要的是, 地方的 变量,其中 远程执行 脚本块无法看到,因此引用未初始化的 变量将有效地产生 $null

    简而言之:你的 调用命令 呼叫不做任何事并返回 $空 是的。


    推荐文章