Check if the network cable is unplugged through PowerShell

In a recent script I did for a customer I needed to check if the network cable is unplugged through PowerShell on clients before continuing to execute the rest of the script.
With PowerShell you can get a lot of information about the network card, but depending on the client you may have more than one card, WiFi for example.

I decided to create a function to check if the cable is connected and send the adapter to this function.

The first step is to identify which adapter we want to check. To do this, we will use the cmdlet “Get-NetAdapter”. Running this on my client results in the following output:

Get-NetAdapter

 

As you can, listed above are my WiFi, VPN, Cable and all my Hyper-V switches.
Trying to check all above is possible, unnecessary though, and in this case “Ethernet” is the one we would like to check.

What we need to check is the object called “PhysicalMediaType”. To do this, simply run:

Get-NetAdapter | select Name, PhysicalMediaType

The output in my case will be:

PhysicalMediaType

 

As shown above, the type of the adapter named “Ethernet” is “802.3”. (This is my cabled connection)

Knowing this, we can save this adapter to a variable, for example “$netadapter”.

$netadapter = Get-NetAdapter | Where-Object PhysicalMediaType -EQ 802.3

The function itself is just a loop that checks every three seconds if the network is up, meaning that a cable is connected.

function CheckCable{
    param(
    [parameter(Mandatory=$true)]
    $adapter
    )

    if($adapter.status -ne "Up"){
        do{
            $adapter = Get-NetAdapter | Where-Object PhysicalMediaType -EQ 802.3
            Start-Sleep -Seconds 3
        }
        until($adapter.Status -eq "Up")
    }
}

So, to use this, simply run:

CheckCable -adapter $netadapter

Note: This is written for computers that only has a single ethernet adapter.

For more PowerShell guides, check the following link:
http://guidestomicrosoft.com/2015/11/02/powershell-guides/

This entry was posted in Powershell and tagged , , , , , . Bookmark the permalink.

One Response to Check if the network cable is unplugged through PowerShell

  1. Pingback: PowerShell Guides - A guide to Microsoft ProductsA guide to Microsoft Products

Leave a Reply

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