Friday, February 19, 2016

Getting an overview of server reboots

A quick one that I wanted to keep for reference, after a forum post on powershell.org. Someone wanted to have a list of reboot times from the eventlog and put it in a text file, so I commented:

$ServerList = Get-Content "C:\Scripts\ServerList.txt"

foreach ($i in $ServerList){
    Write-Output $i "`n"+"==========================" | Out-File -FilePath c:\scripts\ServerRestart.txt -Append

    $Output = Get-EventLog System -ComputerName "$i" | Where-Object {$_.EventID -eq "1074" -or $_.EventID -eq "6008" -or $_.EventID -eq "1076"} | ft Machinename, TimeWritten, UserName, EventID, Message -AutoSize -Wrap

    $Output | Out-File -FilePath c:\scripts\ServerRestart.txt -Append
}

This obviously only works if you have enough credentials to access the remote server. This in itself should do the job for not too many servers, or lots in due time, because it runs on one server at a time.

If you want to kick things up a notch, and parallelize things, you can run it as a job with Invoke-Command with "-Asjob":

$ServerList = Get-Content "C:\Scripts\ServerList.txt"

$block = {Get-EventLog System | Where-Object {$_.EventID -eq "1074" -or $_.EventID -eq "6008" -or $_.EventID -eq "1076"} | ft Machinename, TimeWritten, UserName, EventID, Message -AutoSize -Wrap }

foreach ($Server in $ServerList){
Invoke-Command -ComputerName $Server -ScriptBlock $block -AsJob
}

While (Get-Job -State "Running") {    
    Write-Host -ForegroundColor Yellow "Running..."
    Start-Sleep 1        
}    

Get-Job| Receive-Job |Out-File C:\scripts\ServerRestart.txt
Write-Host -ForegroundColor Yellow "Done!"


Which will give the following output:

Get-Job| Receive-Job |Out-File C:\scripts\ServerRestart.txt

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
35     Job35           RemoteJob       Running       True            localhost            Get-EventLog System | ...
37     Job37           RemoteJob       Running       True            127.0.0.1            Get-EventLog System | ...
Running...
Running...
Running...
Running...
Running...
Done!

This should speed things up a bit, as now all machines run it simultaneously. The only thing that doesn't get done that way is the divider-line at the top.

To be totally neat, you should clean up the jobs too:

Write-Host -ForegroundColor Yellow "Clearing Up completed jobs"
Get-Job -State "Completed" |Remove-Job

Now you should be able to do a Get-Job and see if there are any failed jobs. Yes yes, that could be automated too..

No comments:

Post a Comment