Sierramike
Sierramike

Reputation: 113

How to get network connection type in PowerShell

In a PowerShell script I need to run some commands if the network connection type is not "DomainAuthenticated".

The aim is not to change the connection type manually, but run a set of commands.

I found about Get-NetConnectionProfile, but I can't find how to parse its output :

Name             : MyName
InterfaceAlias   : vEthernet (Port1)
InterfaceIndex   : 19
NetworkCategory  : DomainAuthenticated
IPv4Connectivity : Internet
IPv6Connectivity : NoTraffic

I need to get the type from the line NetworkCategory so I can test its content and run my commands.

Upvotes: 2

Views: 4317

Answers (2)

Michel Balencourt
Michel Balencourt

Reputation: 156

Alternatively, if you put Get-NetConnectionProfile into a variable, you can just call $variable.NetworkCategory. Like this :

PS C:\Windows\system32> $ncp = Get-NetConnectionProfile
PS C:\Windows\system32> $ncp.NetworkCategory
DomainAuthenticated

Upvotes: 0

Spikeh
Spikeh

Reputation: 3695

You can get an individual property value from a powershell object a few ways, but the simplest is to pipe the output to the Select cmdlet:

PS C:\WINDOWS\system32> Get-NetConnectionProfile | Select -ExpandProperty NetworkCategory
Private
Public

I have two entries because I have two network adapters. It entirely depends what you want to do with the output, but something like this might help:

Get-NetConnectionProfile | Select -ExpandProperty NetworkCategory | %{ if($_ -eq "DomainAuthenticated") { Write-Host "Replace Write-Host with what you want to do" } }

% is short-hand for "for each". Select is short-hand for Select-Object.

That's an example of both functional and procedural style scripting in Powershell. You may be able to pipe the output directly to another cmdlet though, and ignore the short-hand - it really does depend what your use-case is.

Upvotes: 4

Related Questions