首页 > 解决方案 > 从 Invoke-Command 返回变量

问题描述

我正在尝试将 Invoke-Command 中的结果数据输出到 .csv 文件,但运气不佳。这是我所拥有的:

$output= @()

    ForEach ($server in $servers) {
        Invoke-Command -ComputerName $server -ScriptBlock {
            param($server_int, $output_int)
            If((Start-Process "c:\temp\installer.exe" -ArgumentList "/S" -Wait -Verb RunAs).ExitCode -ne 0) {
                $output_int += "$server_int, installed successfully"
            } else {
                $output_int += "$server_int, install failed"
            }
        } -ArgumentList $server, $output

    }

$output | Out-file -Append "results.csv

"

据我了解, $output_int 仅在 Invoke-Command 会话中可用。如何检索此 $output_int 变量并将其值添加到我的 .csv 文件中?

非常感谢!

标签: powershell

解决方案


使用Write-Outputcmdlet,并将调用保存到$output数组中...

试试这个:

$output = @()

    ForEach ($server in $servers) {
        $Output += Invoke-Command -ComputerName $server -ScriptBlock {
            param($server_int)
            If((Start-Process "c:\temp\installer.exe" -ArgumentList "/S" -Wait -Verb RunAs).ExitCode -ne 0) {
                Write-Output "$server_int, installed successfully"
            } else {
                Write-Output "$server_int, install failed"
            }
        } -ArgumentList $server
    }

$output | Out-file -Append "results.csv"

推荐阅读