Select Page

I’m relatively new to PowerShell. I’ve known about it and have dabbled with it here and there but as of lately I’ve been digging in a bit deeper. One of my projects was to build a homegrown monitoring system. Being a DBA it’s natural that I would check for all SQL related services. I take advantage of Get-WmiObject and class Win32_Service to gather details like Name (service name), StartName (service account), StartMode, and State and from there I conduct my evaluation. If the service has a startmode of “auto” and a state -ne “running” then my process will fire off an email based alert specific to the server type (i.e. Prod, Dev, QA, etc…) and notify the appropriate resource group. It’s pretty slick and has a very small footprint. I won’t get into all the details but I will share with you the foundation of what I have. By separating the servers into the category: “servertype” I am able to monitor production systems much more aggressively.

The first step is to check and see if the server is online. This can be done by a simple ping or via test-connection (my preferred method). It’s quicker and requires less syntax to obtain the IPv4 address. Here’s a snippet of both. I use a view to retrieve a list of our SQL Servers and pass the parameter: “servertype” to the script and that loads the subset of servers into an array. My process then iterates through all the elements, weeding out online from offline servers to online and offline services.

Here’s the building blocks if you are interested. [Download File]

Clear-Host
<#
	Author			:	Samson J. Loo
    Site            :   http://ayesamson.com
	Date Created	:	2015-06-01
	Script Name		:	MethodsToResolveIPv4
	Description		:	Written to check if server(s) are online using in-line
                        array or from a file (i.e. C:\PS\servers.txt) list.
	Requirements	:	Online Servers, PowerShell
    Tables          :   None
    Procedures      :   None
    Functions       :   None
    Snapins         :   None
	======================================================================
	File Name		:	MethodsToResolveIPv4.ps1
	Version			:	1.00
	======================================================================
    Parameter       :   None
	======================================================================
	Usage			:   Either PS Console or ISE
	======================================================================
	Revisions (Most recent on top)
	======================================================================
	Author			Date			Details
	-------------	-------------	--------------------------------------
	S.Loo			2015-06-01		Initial draft
#>

$servers = @("OnlineServerName","MistypedServerName",$env:COMPUTERNAME)

# IF THE $servers ARRAY IS EMPTY LOAD VALUES FROM FILE.
if ($servers.Length -eq 0) {
    $file = "C:\PS\servers.txt"

    # CHECK IF PATH EXISTS
    if (!(Test-Path $file)) {

        # PATH DOES NOT EXIST. WRITE ERROR TO SCREEN.
        Write-Host "The path or file specified does not exist. (" $file ")" -BackgroundColor Red -ForegroundColor White
        Write-Host "Script terminated."
        Exit

    } #end if

    else {
        # IF EXISTS LOAD INTO ARRAY
        $servers = @(Get-Content $file)

    } #end else

} #end if

Write-Host ""
# METHOD: 1 - USING TEST-CONNECTION

foreach ($server in $servers) {

    if (Test-Connection -ComputerName $server -Count 1 -BufferSize 16 -ea 0 -Quiet) {

        # LOAD IP ADDRESS TO VARIABLE (DO NOT USE THE "-Quiet" KEY ON THE FOLLOWING LINE. IT WILL PREVENT THE IP FROM BEING CAPTURED)
        $ipaddr = Test-Connection $server -Count 1 | Select-Object IPV4Address
        Write-Host $server $ipaddr.IPV4Address

    } #end if

    else {
        Write-Host $server "failed to respond" -BackgroundColor Red -ForegroundColor White

    } #end else

} #end foreach

# METHOD: 2 - USING PING
Write-Host ""
$ping = New-Object System.Net.NetworkInformation.Ping
foreach ($server in $servers) {

    # TRY PROCESS
    try {
        $results = $ping.send($server)
        $ipaddr = $results.Address

            # WORK-AROUND TO RESOLVE IPv4 IF THE HOST RUNNING THE PROCESS IS CHECKING ITSELF
            if ($server -eq $env:COMPUTERNAME) {
                $ipaddr = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]

            } #end if

        if ($results.Status -eq "Success") {
            Write-Host $server $ipaddr

        } #end if

        else {
            Write-Host $server "failed to respond" -BackgroundColor Red -ForegroundColor Yellow

        } #end else

    } #end try

    # TRAP EXCEPTIONS
    catch [System.Exception] {
        Write-Host $server $error[0] -BackgroundColor Red -ForegroundColor White

    } #end catch

} #end foreach
Share This