Thursday, April 26, 2012

Scripting Games 2012 Advanced Event 6

Advanced Event 6 :

<#
.DESCRIPTION
    This script reports information about multiple servers uptime.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/09/2012-scripting-games-advanced-event-6-compute-uptime-for-multiple-servers.aspx
.PARAMETER Computers
    Name of the remote computer, if omitted localhost will be used.
.EXAMPLE
    event6.ps1
    To collect information about error events from local computer, run the script without parameters.
.EXAMPLE
    event6.ps1 "computer1","computer2"
    To collect information about error events on remote computers.
#>

param (
[string[]]$Computers=$env:computername
)
[datetime]$Reptime=(Get-Date -UFormat %D).tostring() + " 08:00:00"
Foreach ($server in $computers)
{
    $os= Get-WmiObject -ea silentlycontinue Win32_OperatingSystem -ComputerName $server
    #check if $os is not null
    if (!($os -eq $null))
    {
       $reboot =$os.ConvertToDateTime($os.LastBootUpTime)
       
        $obj  = New-Object -TypeName PSObject
            if ( $Reptime -ge $reboot )
            {
                $dif = $reptime.Subtract($reboot)
                $obj | Add-Member NoteProperty Computername $server
                $obj | Add-Member NoteProperty Days $dif.days
                $obj | Add-Member NoteProperty Hours $dif.hours
                $obj | Add-Member NoteProperty Minutes $dif.minutes
                $obj | Add-Member NoteProperty Seconds $dif.seconds
                $obj | Add-Member NoteProperty Date $reboot.ToShortDateString()
       
            }
            else
            {
                $obj | Add-Member NoteProperty Computername $server
                $obj | Add-Member NoteProperty Days 0
                $obj | Add-Member NoteProperty Hours 0
                $obj | Add-Member NoteProperty Minutes 0
                $obj | Add-Member NoteProperty Seconds 0
                $obj | Add-Member NoteProperty Date $null
            }

            $filepath = $env:userprofile + "\Documents\" + $Reptime.ToString("yyyyMMdd") + "_Uptime.csv"
                If (Test-Path($filepath))
                {
                    $obj |ConvertTo-Csv -OutVariable OutData -NoTypeInformation
                    $OutData[1..($OutData.count - 1)]  | ForEach-Object {Add-Content -Value $_ -Path $filepath}
                }
                else
                {
                    $obj | Export-Csv -NoTypeInformation -Path $filepath
                }
     }  
}

No comments:

Post a Comment