Friday, August 1, 2014

PowerShell - Get All SQL server VMs last reboot date/time

PowerShell ISE 3.0

The purpose of the following script is to make my DBA life easy when I manage 80 + SQL server VMs in the organization. The following script is to retrieve all SQL Server VM Last reboot date time without logging into each server and check eventlog.


Enjoy Scripting..

Step 1. Create a text file in which all sql server vm names. Save the file in your preferred. In my case the file is located at E:\PowerShell\SQLServerList\ folder
Step 2. run the script in powershell ISE or Schedule it in SQL Agent in your DBA test server instance


$($ServerList = 'E:\PowerShell\SQLServerList\SQLSvrList.txt'
$exportcsv ='E:\PowerShell\FindLastRebootDate\LastRebootDate.csv'
$servername = Get-Content $ServerList
$errorlog = 'E:\PowerShell\FindLastRebootDate\Error.txt'
if(!(test-path $ServerList))
{
    Write-Error "SQLSvrList.txt is not Found" -ea Stop
}
if(test-path $ServerList)
{
foreach($server in $servername){
Try{

$WMI=Get-WmiObject -ComputerName $server -Class win32_operatingsystem
$lastRebootTime = $WMI.ConvertToDateTime($WMI.LastBootUpTime)

$InfoRecord = New-Object -TypeName PSObject -Property @{
                    Server = $server;
                    LastRebootDateTime = $LastRebootTime;
                    };

$InfoRecord | Select Server,LastRebootDateTime


}
Catch
{
    Clear-Content $errorlog
    "Fail to get information $server +' ' + $RunTime :$_" |Out-File $errorlog -Append
}
}
})|Export-csv $exportcsv -noType
Get-Job | Wait-Job | Out-Null
Remove-Job -State Completed

No comments:

Post a Comment

How to add a Database to AlwaysOn Availability Group with four different options

To add a database to an existing AlwaysOn availability group, MS has given us four options to choose from Automatic seeding Full database an...