/
/

How to Audit Open Network Ports Across Remote Clients Using PowerShell and Log Results

by Mauro Mendoza, IT Technical Writer
How to Audit Open Network Ports Across Remote Clients Using PowerShell and Log Results blog banner image

An unmonitored open network port to the internet is a vulnerability waiting to be exploited, exposing remote clients to unnecessary risk. Regularly auditing this port exposure is crucial for enforcing security policies and ensuring only sanctioned services are reachable.

In this guide, you will learn how to use PowerShell to automate these audits at scale, providing deep insight without expensive tooling.

📌Recommended deployment strategies:

Click to Choose a Method

💻

Best for Individual Users

💻💻💻

Best for Enterprises

Method 1: PowerShell
Method 2: Registry
Supporting Method, Option 1: via GPO
Supporting Method, Option 2: via Get-NetUDPEndpoint

We recommend checking ⚠️ Things to look out for before proceeding.

Method to check open network ports with a PowerShell audit

A regular audit of open ports is a fundamental practice for maintaining a secure network. It helps you find and close doors before attackers can use them against you.

📌 Use case: Perform this check in a few key situations: when setting up a new computer to ensure it’s secure, on a regular schedule (like every month), after installing new software, and if you suspect a security issue, to look for signs of an intruder.

📌 Prerequisites: To check if TCP and UDP ports are open across your network, you’ll need a few simple things:

  • Modern Windows devices (Windows 10/11 or Windows Server).
  • Administrator access on those machines.
  • PowerShell Remoting (WinRM) is enabled, or an RMM tool like NinjaOne, to run commands.

Method 1: Audit open network ports via PowerShell

The simplest way to check what ports are open on a Windows 11 machine is by using PowerShell’s native commands, which provide clear, actionable data.

Step-by-step procedure:

  1. Open PowerShell (Admin) or Windows Terminal (Admin).
  2. Run this command to get all listening TCP connections and format the output clearly:
Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess).Name}}

This command filters for only ports in the Listen state and displays the local IP address, port number, process ID (PID), and the name of the executable.

  1. To get the same information for UDP ports (which are connectionless), use the Get-NetUDPEndpoint cmdlet:
Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess).Name}}
  1. To save your audit results for reporting, export the data to a CSV file. This command combines TCP and UDP results into a single log:
$Output = @()
$Output += Get-NetTCPConnection -State Listen | Select-Object @{Name=”Protocol”; Expression={“TCP”}}, LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}}
$Output += Get-NetUDPEndpoint | Select-Object @{Name=”Protocol”; Expression={“UDP”}}, LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}}
$Output | Export-Csv -Path “C:\Audit\LocalPortAudit.csv” -NoTypeInformation

💡Note: This command generates a file named LocalPortAudit.csv in the C:\Audit folder. The console has no output since all results are written directly to the CSV file.

  1. Check if a network port is open on a remote client using PowerShell Remoting (WinRM).

Use the Invoke-Command cmdlet to run the audit on one or more remote PCs. This example checks a computer named CLIENT-PC-01.

Invoke-Command -ComputerName CLIENT-PC-01 -ScriptBlock {
Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess).Name}}
} | Export-Csv “\\YourServer\AuditLogs\CLIENT-PC-01-Ports.csv” -NoTypeInformation

After running this procedure, you will have a detailed log file (CSV) listing every open TCP and UDP port on the target machine, the associated application, and its process ID. This log is your master list for analysis.

💡Note: Replace CLIENT-PC-01 with the actual computer name you want to audit, and adjust the export path (e.g., \\YourServer\AuditLogs\…) to a folder that exists and is accessible in your environment.

Method 2: Use Registry for logging and status tracking

Storing audit results in the Windows Registry creates a permanent, easily accessible record for centralized monitoring tools.

This method works by writing key findings from your PowerShell audit, like the timestamp and the number of open ports, to a dedicated location in the registry (HKLM). It doesn’t configure system features but instead uses the registry as a simple database for status information.

Step-by-step procedure:

  1. Create a custom registry key. Run the following PowerShell scripts on the target Windows 11 machine. It will perform the audit, then save a summary to the Registry.

Perform the port audit:

$OpenTCPPorts = Get-NetTCPConnection -State Listen | Where-Object { $_.LocalAddress -notin @(‘127.0.0.1’, ‘::1’) }
$OpenUDPPorts = Get-NetUDPEndpoint | Where-Object { $_.LocalAddress -notin @(‘127.0.0.1’, ‘::1’) }
$TotalOpenPorts = $OpenTCPPorts.Count + $OpenUDPPorts.Count
  • Create a registry key to store the results (the -Force parameter creates any missing parent folders):

New-Item -Path “HKLM:\SOFTWARE\YourCompanyName\PortAudit” -Force

💡Note: Replace YourCompanyName with a meaningful name for your organization before running the command.

  • Store the data:
Set-ItemProperty -Path “HKLM:\SOFTWARE\YourCompanyName\PortAudit” -Name “LastAuditTime” -Value (Get-Date -Format “yyyy-MM-dd HH:mm:ss”)
Set-ItemProperty -Path “HKLM:\SOFTWARE\YourCompanyName\PortAudit” -Name “OpenPortsCount” -Value $TotalOpenPorts
  1. Validate the data. You can quickly verify that the data was written correctly using the Command Prompt:

reg query “HKLM\SOFTWARE\YourCompanyName\PortAudit”

  1. Integrate with monitoring tools like NinjaOne or a scheduled task. It will help you check if a network port is open by reading the OpenPortsCount value.
    • A value higher than a set baseline could automatically trigger an alert for a technician to investigate.

After this procedure, your remote clients will have a standardized registry location containing their last audit results. This allows your central monitoring system to efficiently gather this status information from thousands of machines instantly..

Supporting methods to standardize open port policies

Use Group Policy to proactively control which ports are allowed open, ensuring consistent security across all your Windows 11 devices.

📌 Use case: Deploy these settings when setting up a new security baseline or to enforce compliance standards across your network. This is a preventative measure, not just detection.

📌 Prerequisites: Before proceeding, ensure you have a Windows Active Directory domain, Windows 10/11 Pro, Enterprise, or Education on all clients, and permission to create and manage Group Policies.

Option 1: Use GPO to harden and standardize open port rules

Use Group Policy to proactively define and enforce which ports are allowed open, creating a consistent, secure configuration across your entire network.

📌 Use case: This method works by centrally pushing firewall rules from a domain controller to all Windows 11 clients, overriding any local settings. It is effective because it applies the principle of least privilege, ensuring only approved services can communicate.

Step-by-step procedure:

  1. Navigate to firewall settings in GPO.
    • On your domain controller, open the Group Policy Management Console (gpmc.msc).
    • Create a new GPO or edit an existing one.
    • Navigate to Computer Configuration > Policies > Windows Settings > Security Settings > Windows Firewall with Advanced Security > Inbound Rules.
  2. Create and configure rules.
    • Right-click in the Inbound Rules pane, then select New Rule….
    • Use the wizard to create rules that:
      • Block inbound RDP (port 3389) unless a specific rule is created to allow it from a secure management VLAN or over a VPN.
      • Deny access for guest services and legacy, insecure protocols like SMBv1.
      • Enforce application-based exceptions (e.g., allowing %ProgramFiles%\YourApp\yourapp.exe) instead of opening broad port ranges.
      • Use the “Allow only if secure” option when possible to restrict connections to digitally signed programs.

After linking this GPO to your organizational unit, all affected computers will automatically receive and apply these firewall rules.

This will immediately block unauthorized access attempts on specified ports, significantly reducing the attack surface. Your environment will now have a hardened, uniform configuration that is much more resistant to lateral movement and exploitation.

Option 2: Optional use of Get-NetUDPEndpoint for UDP port coverage

A full port audit must include UDP endpoints, as they can present overlooked security risks. This method works by using the Get-NetUDPEndpoint cmdlet, which queries the Windows network stack to list all active UDP listeners.

📌 Use case: Always include a UDP audit as part of your regular security baseline checks and any comprehensive port audit to get a complete picture of all network-facing services on a Windows 11 device.

Step-by-step procedure:

  1. Audit UDP listeners.

Open an elevated PowerShell window and run the following command to see all open UDP ports and the processes using them:

Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}}
  1. Combine TCP and UDP Results into a Single Report.

For a complete audit, combine the results of your TCP and UDP scans into one report. The script below does this and saves everything to a CSV file.

  • Get all listening TCP ports:
$tcp = Get-NetTCPConnection -State Listen | Where-Object { $_.LocalAddress -notin @(‘127.0.0.1’, ‘::1’) } | Select-Object @{Name=”Protocol”; Expression={“TCP”}}, LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}}
  • Get all UDP endpoints:
$udp = Get-NetUDPEndpoint | Where-Object { $_.LocalAddress -notin @(‘127.0.0.1’, ‘::1’) } | Select-Object @{Name=”Protocol”; Expression={“UDP”}}, LocalAddress, LocalPort, OwningProcess, @{Name=”ProcessName”; Expression={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}}
  • Combine the results and export to a CSV file:
$tcp + $udp | Export-Csv -Path “C:\Audit\Full_Port_Audit_Report.csv” -NoTypeInformation

After running this procedure, you will have a single, consolidated log file that details every open TCP and UDP port on the system.

This holistic view is critical for true security hardening, allowing you to identify and investigate any unauthorized UDP listener with the same efficiency as a TCP one, ensuring your audit of open ports is truly complete.

⚠️ Things to look out for

This section highlights potential challenges to keep in mind while following this guide.

RisksPotential ConsequencesReversals
1. WinRM Not Enabled or AccessibleInability to execute remote PowerShell commands halts automated audits across the network.Enable PSRemoting via GPO or run Enable-PSRemoting -Force on the target client. Ensure that the Windows firewall allows port 5985 (HTTP) or 5986 (HTTPS).
2. Running Scripts Without ElevationIncomplete audit data; critical ports may not be captured, and processes may fail to resolve, leading to a false sense of security.Always run PowerShell as Administrator. For remote execution, ensure your context (e.g., RMM agent) has SYSTEM or admin privileges.
3. Overly Restrictive GPO Firewall RulesGroup Policy breakdown from blocking essential ports (RPC, SMB); Widespread loss of network connectivity and administrative access
  • Local Fix: Log in locally and run gpupdate /force or netsh advfirewall reset.
  • DC Fix: Disable the problematic GPO from the Domain Controller.
4. Registry Access Denied ErrorsFailure to write audit summary data to HKLM:, preventing centralized monitoring and reportingEnsure the script runs in a context with sufficient privileges (e.g., LocalSystem account via an RMM tool). Manually validate permissions on the registry key.
5. Terminating a Process Based Solely on Its PortApplication or critical system service failure, causing downtime and potential data lossRestart the terminated service or reboot the machine. Always investigate the process name and purpose before taking action.
6. Ignoring UDP Ports in the AuditMissing critical security exposures, as malware and unauthorized services often use UDP for communication and data exfiltrationRe-run the audit using the Get-NetUDPEndpoint cmdlet and include it in all future baseline checks.

Key considerations to optimize your port audit strategy

A successful port audit strategy requires careful planning beyond running the commands themselves.

Remote Audit Scaling

To check what ports are open across your entire network, you must automate the process. Use PowerShell’s Invoke-Command to run across a list of computers, or leverage an RMM tool like NinjaOne to push the audit script to all endpoints simultaneously.

This allows you to gather a centralized report from hundreds of devices in minutes, making it practical to audit open ports regularly.

Minimizing False Positives

Not every open port is a vulnerability. Internal loopback addresses (127.0.0.1::1) indicate services talking to the local machine and are often safe.

Filter these out in your scripts to focus your report on ports bound to the machine’s physical IP addresses, which are exposed to the network and represent a more relevant security concern.

Accounting for Firewall Misalignment

An open port on a device doesn’t always mean it’s reachable from the internet. An upstream network firewall or the device’s own Windows Firewall may be blocking external access.

Your audit tells you what is listening; you must correlate this with firewall rules to understand what is truly exposed. Always verify critical findings.

Establishing a Regular Cadence

A single audit is just a snapshot. To maintain ongoing security, run these audits on a regular schedule, such as monthly or aligned with your monthly patch cycles. This ensures you catch any new, unauthorized services quickly and can validate that recent software deployments haven’t introduced unexpected network exposure.

How NinjaOne simplifies port auditing

NinjaOne integrates directly with your port audit workflow to automate and simplify the process.

  • Deploy Scripts Easily: Push custom PowerShell scripts to check what ports are open across all endpoints from a central dashboard.
  • Centralize Results: Automatically store audit findings, like port counts, in a unified registry for easy reporting and review.
  • Get Proactive Alerts: Trigger instant notifications if unauthorized ports (e.g., SMBv1, Telnet) are discovered on any device.
  • Generate Compliance Reports: Create scheduled reports on open port status for client reviews and compliance audits.
  • Prioritize Remediation: Automatically tag devices with high-risk exposures for immediate technician attention.

Secure your network by managing open ports

Regularly auditing for any network ports open on your clients is a critical defense against unauthorized access and potential breaches. This guide provides practical methods to audit and manage open ports.

By implementing these steps, you transform unknown risks into managed assets, significantly strengthening your security posture and ensuring compliance across your entire environment.

Related topics

You might also like

Ready to simplify the hardest parts of IT?