PowerShell : Check if Machine is Up or Down

In this article, I am going write Powershell script to check if a given computer is up (online) or down (offline) and script to check ping status of set of remote machines (from text file-txt) and export its output to CSV file.

PowerShell script to find if a Machine is Online or Offline

We can use the powrshell cmdlet Test-Connection to send a ping command to remote computer to check whether the remote machine is up or down. We can pass the parameter –Quiet to returns only True or False instead of test connection failed error.

$remoteComputer = "hp-PC"
IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $remoteComputer -Quiet) {
        Write-Host "The remote machine is Online"
} Else {
        Write-Host "The remote machine is Down"
}

Check Ping status for set of Remote Computers

Use the below powershell script to test connectivity for set of remote computers. Give the set of machine names as string Array.

$computers = "pc1","pc2","svr1","hp-pc"
Foreach($c in $computers) {
IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $c -Quiet) {
        Write-Host "The remote computer " $c " is Online"
} Else {
        Write-Host "The remote computer " $c " is Offline"
}}

Export Ping status of set of Computers to CSV file

Use the below powershell script to find ping status for multiple remote computers. First create the text file RemoteComputers.txt which includes one machine name in each line. You will get the hostname and its ping status in the CSV file PingStatus.csv.

Get-Content C:RemoteComputers.txt | ForEach-Object{
$pingstatus = ""
IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $_ -Quiet) {
        $pingstatus = "Online"
} Else {
        $pingstatus = "Offline"
}

New-Object -TypeName PSObject -Property @{
      Computer = $_
      Status = $pingstatus }
} | Export-Csv C:PingStatus.csv -NoTypeInformation -Encoding UTF8
Advertisement

4 thoughts on “PowerShell : Check if Machine is Up or Down”

  1. Hi saw your samples. Is there a way to put in a specific IP address and port to the last sample, "export ping status of set of computers to CSV file:"?

    Reply
  2. Receiving the error below from example #3:

    Test-Connection : Cannot validate argument on parameter ‘ComputerName’. The argument is null or empty. Provide an
    argument that is not null or empty, and then try the command again.
    At C:\PS_Bitlocker_Decrypt\Check-Online-PCs.ps1:3 char:59
    + IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $_ -Quiet) …
    + ~~
    + CategoryInfo : InvalidData: (:) [Test-Connection], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand

    Reply

Leave a Comment