Aerondight
Aerondight

Reputation: 137

Empty variable after Invoke-Command

I want to get the most errors of a list of servers and save it in the variable $AllErrors.

But the variable is empty if I want to print it out.

Is there a way to pass the variable out of the Invoke-Command?

This is my code:

Get-Content -Path C:\Users\$env:USERNAME\Desktop\Server.txt |
    ForEach-Object{
        Invoke-Command -ComputerName $_ -ScriptBlock{

            $Date = (Get-Date).AddHours(-12)
            $Events = Get-WinEvent -FilterHashtable @{LogName = 'System'; StartTime = $Date; Level = 2}
            $Errors = $Events | Group-Object -Property ID -NoElement | Sort-Object -Property Count -Descending |
                Select-Object -Property Name -First 1

        }
    }
$Errors | Out-File -FilePath C:\Users\$env:USERNAME\Desktop\AllErrors.txt

Upvotes: 0

Views: 368

Answers (1)

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

No, it's not possible, however you can assign the output of Invoke-Command to a variable. $Errors seems to be the only output of your Invoke-Command, so this should work. But looking at your code you will only get Errors for the last computer as you are constantly overwriting the $Errors variable in cycle. You should either declare $Errors outside of cycle, and append errors to it, or append to file after each cycle:

Get-Content -Path C:\Users\$env:USERNAME\Desktop\Server.txt |
ForEach-Object{
    $Errors = Invoke-Command -ComputerName $_ -ScriptBlock{

        $Date = (Get-Date).AddHours(-12)
        $Events = Get-WinEvent -FilterHashtable @{LogName = 'System'; StartTime = $Date; Level = 2}
        $Events | Group-Object -Property ID -NoElement | Sort-Object -Property Count -Descending |
            Select-Object -Property Name -First 1
        }
        $Errors | Out-File -FilePath C:\Users\$env:USERNAME\Desktop\AllErrors.txt -Append        
    }

Upvotes: 2

Related Questions