0

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

1 Answer 1

2

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        
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.