Powershell - 从远程机器上运行 exe 的 Invoke-Command 捕获输出

Mik*_*uno 2 powershell invoke-command

我需要在一组远程服务器上配置审计策略。我正在尝试使用 Invoke-Command commandlet 在每台服务器上运行 auditpol.exe。问题是我似乎无法从 auditpol 命令中捕获任何输出。

我尝试了显而易见的(将 Invoke-Command 的结果分配给一个字符串):

> $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
>
Run Code Online (Sandbox Code Playgroud)

但是 $out 是空的。

我还使用 Wait-Job 和 Receive-Job尝试了此 MSDN 博客中详述的方法。结果有些令人鼓舞,但尚无定论:

> $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
>
Run Code Online (Sandbox Code Playgroud)

我希望我能够使用 Receive-Job 从 auditpol.exe 捕获实际输出,但如上所述,情况似乎并非如此。

我确实从Wait-Job 那里得到了一些信息。根据Microsoft 文档的 Wait-Job State=Completed应该表明操作成功,但我并不完全相信它真的可以了解 auditpol 操作是否成功。任何建议将不胜感激!

mkl*_*nt0 8

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

$out = Invoke-Command -ComputerName MyServer -ScriptBlock {
  auditpol.exe /set /subcategory 'File System' /success:enable
}
Run Code Online (Sandbox Code Playgroud)

如果您还想捕获stderr输出,请附加2>&1auditpol.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
Run Code Online (Sandbox Code Playgroud)

至于你尝试什么

$out = Invoke-Command -ComputerName MyServer -ScriptBlock {$command}
Run Code Online (Sandbox Code Playgroud)

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

通常,简单地引用一个变量会输出它的值——它不执行任何操作。

然而,更重要的$command是一个局部变量,远程执行的脚本块无法看到它,因此引用那里未初始化的$command变量将有效地产生$null.

简而言之:您的Invoke-Command电话不做任何事情并返回$null.