Thursday, November 3, 2016

How To Check Server Status Windows PowerShell

Overview

In this post / snippet we will demonstrate, check server status utilizing ping command result output and writing the output to a “CSV” file.

This script will read the server name(s) from a file and loop through.

Applies To


Windows 10, Windows 2008 R2, Windows 2012.

Pre-Requisites

Launch PowerShell Command Console or PowerShell ISE.

To run this script, Execution Policy should be set to either of these “AllSigned” or “RemoteSigned” or “Unrestricted”, you can get current execution policy by running the command; “Get-ExecutionPolicy”


Policy Type Purpose
Restricted No scripts can be run. Windows PowerShell can be used only in interactive mode.
AllSigned Only scripts signed by a trusted publisher can be run.
RemoteSigned Downloaded scripts must be signed by a trusted publisher before they can be run.
Unrestricted No restrictions; all Windows PowerShell scripts can be run.

PowerShell Script - Check Server’s Status

This script will test servers listed in “ServersList.txt” file, wherein it will ping and if the server is alive it will write output to CSV file “Host Name” and “Up / Down”.

PowerShell - Code Snippet


#
# Declare Variables
#
$OutputFileName="Server_Status.csv"
$ServersList="c:\temp\ServersList.txt"
#
# Write Column Heading delimited by Tab
#
echo "Host Name`tNode Status" > $OutputFileName
#
# Read hostname(s) from file and assign to variable
#
$ServerNames = Get-Content $ServersList
#
# Loop Each Server and do ping test once
#
foreach ($ServerName in $ServerNames) {
    $StartCount = 0
    $TotalCount = (Get-Content $ServersList | Measure-Object | Select-Object -ExpandProperty Count)
    # 
    # Test Node reachability 
    #  
    if ( Test-Connection -ComputerName $ServerName -Count 1 -ErrorAction SilentlyContinue ) {
    #  
    # Write Node Up, delimited by tab
    #  
        echo "$ServerName`tUp" >> $OutputFileName
    }
    else {
    #  
    # Write Node Down, delimited by tab
    #  
        echo "$ServerName`tDown" >> $OutputFileName
    }

    $StartCount++
    #
    # Progress Bar
    #
    Write-Progress -Activity "Collate Host Status" -Status "Pinging Hosts..." -PercentComplete ($StartCount / $TotalCount *100) 
}
#
# Launch Ping Status Output File
#
Invoke-Item $OutputFileName

PowerShell - Script Output

In this example we will check for 3 servers only.



Slideshare Information

Step by step document with screenshots is uploaded to slideshare.

No comments:

Post a Comment