Norskyi
Norskyi

Reputation: 151

Return variable from Invoke-Command

I am trying to output result data from within Invoke-Command to an .csv file with little luck. Here is what I have:

$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

"

As I understand, $output_int is only available within the Invoke-Command session. How do I go about retrieving this $output_int variable and add it's value/s to my .csv file?

Many thanks!

Upvotes: 0

Views: 2491

Answers (1)

Avshalom
Avshalom

Reputation: 8899

Use Write-Output cmdlet, and save the invocation into the $output array...

Try this:

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

Upvotes: 1

Related Questions