Use PowerShell function to check if servers are accessible

Recently I had to check quickly if all of managed servers are accessible. As SCOM monitoring wasn’t set yet in my environment I had to create simple script to do that. One of the easiest method to check if server is up is to test availability of network share.

Test-Path

There are many ways to check if server is accessible like for example using ping, checking some specific service but for me this was the fastest way. In simple words script is just based on Test-Path command which basically return true or false value:

$SMB = Test-Path "\\$server\c$"

For more information about Test-Path you can check technet site.

Usage:

Test-Server -ComputerName Server1,Server2,Server3 -Verbose
Test-Server -ComputerName Server1,Server2,Server3 | Out-GridView
Test-Server -ComputerName (Get-Content "C:\temp\servers.txt") |  Export-Csv -Path C:\users\$env:username\desktop\results.csv -NoTypeInformation

Output:
Results we will be presented in two columns "Server" and "Is Online". If network path is accessible on remote server then it returns true value.

Test-Server
Test-Server

Final script:


Function Test-Server {
        [CmdletBinding()]
               
        # Parameters used in this function
        param
        ( 
            [Parameter(Position=0, Mandatory = $true, HelpMessage="Provide server names", ValueFromPipeline = $false)] 
            $ComputerName
        ) 

        $Array = @()

        ForEach($Server in $ComputerName)
        {
            $Server = $Server.Trim()

            Write-Verbose "Checking $Server"

            $SMB = $null
            $Object = $null
            $Status = $null

            $SMB = Test-Path "\\$server\c$"

            If($SMB -eq "True")
            {
                Write-Verbose "$Server is up"
                $Status = "True"
                $Object = New-Object PSObject -Property ([ordered]@{ 
                     
                    Server                = $Server
                    "Is Online?"          = $Status
                })
   
                $Array += $Object
            }
            Else
            {
                Write-Verbose "$Server is down"
                $Status = "False"
                $Object = New-Object PSObject -Property ([ordered]@{ 
                     
                    Server                = $Server
                    "Is Online?"          = $Status
 
                })
   
                $Array += $Object
            }
        }

    If($Array)
    {
        return $Array
    }
}

I hope that this was informative for you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *