How to Use PowerShell to Perform a Network Connection Profile Check on Windows

Managing endpoint connectivity is critical for system administrators and managed service providers (MSPs). Misconfigured network profiles can inadvertently introduce security risks or limit resource access. Accurately identifying whether a device is on a public, private, or domain network can make all the difference when configuring firewalls, deploying policies, or troubleshooting connectivity. For IT professionals looking to streamline this process, a PowerShell script for network connection profile checks offers automation, insight, and consistency across large device fleets.

Background

In enterprise and MSP environments, a device’s network profile directly impacts its security stance. For example, public profiles generally trigger stricter firewall rules than private or domain profiles. Knowing which network each adapter is using can help IT teams spot misclassifications and enforce the correct settings.

While Windows provides GUI-based tools for checking network status, these are not scalable. This PowerShell-based script not only identifies network profiles across adapters but also integrates with NinjaOne by optionally updating a custom field—empowering admins to programmatically collect and act on network configuration data. It’s a useful tool in the broader context of endpoint visibility and compliance auditing.

The Script

#Requires -Version 5.1

<#
.SYNOPSIS
    Checks the current network connections to see what profile they are currently using and optionally save the results to a custom field.
.DESCRIPTION
    Checks the current network connections to see what profile they are currently using and optionally save the results to a custom field.
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.EXAMPLE
    (No Parameters)
    
    Retrieving network adapters.
    Gathering additional information.

    NetworkAdapter   MacAddress        Type  Profile
    --------------   ----------        ----  -------
    LabNet - Win10 0 00-17-FB-00-00-02 Wired  Public

PARAMETER: -CustomField "ReplaceMeWithYourDesiredCustomField"
    Optionally specify the name of a custom field to save the results to.

.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes: Initial Release
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$CustomField
)

begin {
    # If script form variables are used, replace the command the command line parameters with their value.
    if ($env:networkProfileCustomFieldName -and $env:networkProfileCustomFieldName -notlike "null") { $CustomField = $env:networkProfileCustomFieldName }
    
    function Set-NinjaProperty {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory = $True)]
            [String]$Name,
            [Parameter()]
            [String]$Type,
            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
            $Value,
            [Parameter()]
            [String]$DocumentName
        )
        
        # Measure the number of characters in the provided value
        $Characters = $Value | ConvertTo-Json | Measure-Object -Character | Select-Object -ExpandProperty Characters
    
        # Throw an error if the value exceeds the character limit of 200,000 characters
        if ($Characters -ge 200000) {
            throw [System.ArgumentOutOfRangeException]::New("Character limit exceeded: the value is greater than or equal to 200,000 characters.")
        }
        
        # Initialize a hashtable for additional documentation parameters
        $DocumentationParams = @{}
    
        # If a document name is provided, add it to the documentation parameters
        if ($DocumentName) { $DocumentationParams["DocumentName"] = $DocumentName }
        
        # Define a list of valid field types
        $ValidFields = "Attachment", "Checkbox", "Date", "Date or Date Time", "Decimal", "Dropdown", "Email", "Integer", "IP Address", "MultiLine", "MultiSelect", "Phone", "Secure", "Text", "Time", "URL", "WYSIWYG"
    
        # Warn the user if the provided type is not valid
        if ($Type -and $ValidFields -notcontains $Type) { Write-Warning "$Type is an invalid type. Please check here for valid types: https://ninjarmm.zendesk.com/hc/en-us/articles/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality" }
        
        # Define types that require options to be retrieved
        $NeedsOptions = "Dropdown"
    
        # If the property is being set in a document or field and the type needs options, retrieve them
        if ($DocumentName) {
            if ($NeedsOptions -contains $Type) {
                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2>&1
            }
        }
        else {
            if ($NeedsOptions -contains $Type) {
                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2>&1
            }
        }
        
        # Throw an error if there was an issue retrieving the property options
        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }
            
        # Process the property value based on its type
        switch ($Type) {
            "Checkbox" {
                # Convert the value to a boolean for Checkbox type
                $NinjaValue = [System.Convert]::ToBoolean($Value)
            }
            "Date or Date Time" {
                # Convert the value to a Unix timestamp for Date or Date Time type
                $Date = (Get-Date $Value).ToUniversalTime()
                $TimeSpan = New-TimeSpan (Get-Date "1970-01-01 00:00:00") $Date
                $NinjaValue = $TimeSpan.TotalSeconds
            }
            "Dropdown" {
                # Convert the dropdown value to its corresponding GUID
                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header "GUID", "Name"
                $Selection = $Options | Where-Object { $_.Name -eq $Value } | Select-Object -ExpandProperty GUID
            
                # Throw an error if the value is not present in the dropdown options
                if (!($Selection)) {
                    throw [System.ArgumentOutOfRangeException]::New("Value is not present in dropdown options.")
                }
            
                $NinjaValue = $Selection
            }
            default {
                # For other types, use the value as is
                $NinjaValue = $Value
            }
        }
            
        # Set the property value in the document if a document name is provided
        if ($DocumentName) {
            $CustomField = Ninja-Property-Docs-Set -AttributeName $Name -AttributeValue $NinjaValue @DocumentationParams 2>&1
        }
        else {
            # Otherwise, set the standard property value
            $CustomField = $NinjaValue | Ninja-Property-Set-Piped -Name $Name 2>&1
        }
            
        # Throw an error if setting the property failed
        if ($CustomField.Exception) {
            throw $CustomField
        }
    }

    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    if (!$ExitCode) {
        $ExitCode = 0
    }
}
process {
    # Check if the script is running with elevated (Administrator) privileges.
    if ($CustomField -and !(Test-IsElevated)) {
        Write-Host -Object "[Error] Access Denied. Administrator privileges are required to set Custom Fields."
        exit 1
    }

    # Initialize a list to store network information.
    $NetworkInfo = New-Object System.Collections.Generic.List[object]

    # Inform the user that network adapters are being retrieved.
    Write-Host -Object "Retrieving network adapters."

    try {
        # Attempt to retrieve the network connection profiles and adapters.
        $NetworkProfiles = Get-NetConnectionProfile -ErrorAction Stop
        $NetworkAdapters = Get-NetAdapter -ErrorAction Stop
    }
    catch {
        # Catch any errors during network profile/adapter retrieval and output error messages.
        Write-Host -Object "[Error] Failed to retrieve network adapters."
        Write-Host -Object "[Error] $($_.Exception.Message)"
        exit 1
    }

    # Inform the user that additional information is being gathered.
    Write-Host -Object "Gathering additional information."

    # Loop through each network profile.
    foreach ($NetworkProfile in $NetworkProfiles) {
        # Find the network adapter associated with the current network profile using the InterfaceIndex.
        $NetAdapter = $NetworkAdapters | Where-Object { $_.ifIndex -eq $NetworkProfile.InterfaceIndex }

        # Determine the adapter type (Wired, Wi-Fi, or Other) based on the MediaType.
        switch -Wildcard ($NetAdapter.MediaType) {
            "802.3" { $AdapterType = "Wired" }
            "*802.11" { $AdapterType = "Wi-Fi" }
            default { $AdapterType = "Other" }
        }

        # Add the network adapter information as a custom object to the $NetworkInfo list.
        $NetworkInfo.Add(
            [PSCustomObject]@{
                "NetworkAdapter" = $NetAdapter.Name
                "MacAddress"     = $NetAdapter.MacAddress
                "Type"           = $AdapterType
                "Profile"        = $NetworkProfile.NetworkCategory
            }
        )
    }

    # Check if the $NetworkInfo list is empty or contains fewer than one entry.
    if (!$NetworkInfo -or ($NetworkInfo | Measure-Object | Select-Object -ExpandProperty Count) -lt 1) {
        Write-Host -Object "[Error] No network interfaces found."
        exit 1
    }

    # Format and output the network information in a table.
    Write-Host -Object ""
    ($NetworkInfo | Format-Table | Out-String).Trim() | Write-Host
    Write-Host -Object ""

    # If a custom field is provided, iterate through the network information and append the adapter details to $CustomFieldValue.
    if ($CustomField) {
        $NetworkInfo | ForEach-Object {
            if ($CustomFieldValue) {
                # Append the network adapter name and profile to the existing $CustomFieldValue.
                $CustomFieldValue = "$CustomFieldValue | $($_.NetworkAdapter): $($_.Profile)"
            }
            else {
                # Set $CustomFieldValue if it hasn't been initialized yet.
                $CustomFieldValue = "$($_.NetworkAdapter): $($_.Profile)"
            }
        }

        try {
            # Try to set the custom field value using the Set-NinjaProperty function.
            Write-Host "Attempting to set Custom Field '$CustomField'."
            Set-NinjaProperty -Name $CustomField -Value $CustomFieldValue
            Write-Host "Successfully set custom field '$CustomField'!"
        }
        catch {
            Write-Host "[Error] $($_.Exception.Message)"
            exit 1
        }
    }

    # Exit the script with the provided $ExitCode variable.
    exit $ExitCode
}
end {
    
    
    
}

 

Detailed Breakdown

This script is a robust tool built with modular functions and administrative awareness. Here’s a breakdown of its core components:

1. Parameter Handling

The script accepts an optional parameter -CustomField, which allows it to store the network profile summary into a NinjaOne custom field. This can also be passed via environment variable, useful for automation contexts.

2. Privilege Verification

Before performing actions that require elevated rights—like writing to custom fields—it checks whether it’s running with administrator privileges using the Test-IsElevated function. If not, it aborts with an error.

3. Retrieving Network Data

It pulls data using:

powershell

CopyEdit

$NetworkProfiles = Get-NetConnectionProfile

$NetworkAdapters = Get-NetAdapter

The script matches each network profile to its corresponding adapter by InterfaceIndex, determines the adapter type (e.g., “Wired”, “Wi-Fi”, “Other”), and stores everything in a PSCustomObject.

4. Formatting Output

All network info is compiled into a table with:

  • Network Adapter Name
  • MAC Address
  • Connection Type
  • Current Profile (Public, Private, or Domain)

This formatted output is printed directly to the console.

5. Integration with NinjaOne

If the -CustomField parameter is provided, the script uses the Set-NinjaProperty function to save the adapter:profile mapping into a NinjaOne custom field. This includes:

  • Value serialization
  • Type validation (e.g., checking if the field is a Dropdown)
  • Optional documentation linking

This function includes guardrails like a 200,000-character limit and error handling.

Potential Use Cases

Imagine an MSP onboarding a new client’s 200 laptops across multiple sites. A script like this could be deployed via NinjaOne’s automation system to capture each device’s network context. Devices mistakenly configured for the “Public” profile while on a secure corporate LAN can be flagged for correction. Meanwhile, this data is stored in NinjaOne’s custom fields, making it accessible for dashboards or automated alerts.

Comparisons

Compared to manually checking profiles via GUI or one-off PowerShell commands like Get-NetConnectionProfile, this script:

  • Scales effortlessly across hundreds of endpoints.
  • Standardizes data capture with consistent formatting.
  • Integrates with NinjaOne for post-run visibility and documentation.
  • Supports documentation via custom field linkage, adding long-term utility.

Other approaches such as using WMI or third-party agents might offer more granularity but add complexity and latency. This script hits the sweet spot for simplicity, visibility, and actionable output.

FAQs

Q: Do I need to run this script as an administrator?

Yes, especially if you’re writing to a custom field. Otherwise, it will only display information and exit gracefully.

Q: Can I run this without NinjaOne integration?

Absolutely. If you don’t provide the -CustomField parameter, the script simply reports network data to the console.

Q: What network types does it detect?

It categorizes adapters into “Wired”, “Wi-Fi”, or “Other” based on MediaType.

Q: How are multiple adapters handled?

Each active adapter is listed individually, and their network profile is included in the output and/or stored in the custom field.

Implications

A misconfigured network profile could expose endpoints to undue risk. For example, an internal laptop on a corporate VLAN should never be classified under a “Public” network profile, which could disable critical access or restrict group policy applications. This script surfaces those misalignments quickly, allowing IT teams to correct them before they become vulnerabilities.

Recommendations

  • Schedule Regular Checks: Automate this script to run on a weekly cadence via NinjaOne.
  • Use with Custom Fields: Storing results enables historical tracking and report generation.
  • Alert on Misclassifications: Pair this script with policy-based alerts to flag public profiles in secure locations.
  • Run with Elevated Rights: For full functionality, ensure scripts run with admin privileges.

Final Thoughts

This PowerShell script for network connection profile checks exemplifies how automation can reduce manual overhead while improving visibility and security. When used alongside NinjaOne’s powerful scripting and custom field framework, it gives IT teams a scalable way to monitor, log, and respond to misconfigured network states—right from a single pane of glass.

Whether you’re auditing a few endpoints or managing thousands, this script should be part of your automation toolkit.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service delivery tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).