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:
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:
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:
https://guidestomicrosoft.com/2015/11/02/powershell-guides/
Pingback: PowerShell Guides - A guide to Microsoft ProductsA guide to Microsoft Products