r/PowerShell • • Jun 02 '26

Script Sharing Events are Easy

115 Upvotes

Events are easy.

Events let you know when something happened, and respond to it if you choose.

Events are incredibly useful.

Why?

Because they let you run what you want, when you want.

Let's see how simple they are:

Creating Events

Events are easy to create.

To make a new event, simply run:

New-Event MyCustomEvent

This will output an event object.

If nothing subscribes to the event, the event will go in the queue

We can get events with:

Get-Event

We can handle these events whenever we want.

How about now?

Subscribing to Events

We can run code the millisecond something happens.

To do this, we can subscribe to the event.

There are two types of events we can subscribe to in PowerShell:

Engine events and object events.

Engine Events

We can create engine events with New-Event.

We can subscribe to engine events with Register-EngineEvent

$subscriber = Register-EngineEvent -SourceIdentifier "Hello World" -Action {
    "Hello World" | Out-Host
}
$helloWorld = New-Event -SourceIdentifier "Hello World" 

You might notice a cool thing here: An event's "Source Identifier" can be whatever we want.

Let's pass along a message:

$subscriber = Register-EngineEvent -SourceIdentifier "Print Message" -Action {
    $event.MessageData | Out-Host
}
$printMessageEvent = New-Event -SourceIdentifier "Print Message" -MessageData "Hello World"

If you run these scripts multiple times, you'll quickly notice that multiple subscriptions are allowed.

The cool thing to note here is that event subscribers share data in their $event.MessageData

Let's demonstrate this by counting twice.

$doubleCounter = foreach ($n in 1..2) {
    Register-EngineEvent -SourceIdentifier "Counter" -Action {
        $event.MessageData.Counter++
        $event.MessageData.Counter | Out-Host
    }
}

$counterEvent = New-Event -SourceIdentifier "Counter" -MessageData @{
    Counter=0
}

Every time we run this block of code, we get two more subscriptions and a bunch more output.

Before we clean up, let's talk about object events

Object Events

PowerShell is built on the .NET framework. .NET already has events all over the place.

Let's start simple, with a timer:

# Create a timer
$timer = [Timers.Timer]::new([Timespan]"00:00:03")
# don't automatically reset (we only want to do this once)
$timer.AutoReset = $false

# Subscribe to our event
$inAFew = Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action {
    "In a few seconds" | Out-Host
}

# Start the timer (see a message in a few seconds)
$timer.Start()

Lots of .NET types have events.

To see if any object supports events, simply pipe it to Get-Member (events will be near the top).

Timers are a good start. What about watching for file changes?

$watcher = [IO.FileSystemWatcher]::new($pwd)

Register-ObjectEvent -InputObject $watcher -EventName Changed -Action {
    $changedFile = $event.SourceArgs[1].Fullpath
    $changedFile | Out-Host
    $changedFile
} 

'Check this out' > ./What-File-Changed.txt

This is just the tip of the iceberg.

There are literally millions of .NET types out there.

They can all have events.

And we can subscribe to these events in PowerShell

Getting Subscribers

Let's start to clean up a bit:

To get any current subscribers, we can use Get-EventSubscriber

Get-EventSubscriber

To get events subscribing to a source, we can use:

Get-EventSubscriber -SourceIdentifier "Hello World"

If a subscriber has an .Action, we can get results of that action by piping to Receive-Job

This pipeline will get any output from any subscriber with an action

Get-EventSubscriber |
    Where-Object Action |
        Select-Object -ExpandProperty Action |
            Receive-Job -Keep

Hopefully this will help make another part of event subscriptions "click":

Not only can we run code in the background: we can easily get the results, too.

Cleaning Up

We can unsubscribe by using Unregister-Event

# Unsubscribe from everything
Get-EventSubscriber | Unregister-Event

While we're cleaning up, let's also take care of any events in the queue.

We can do this with Remove-Event

# Get all events, and remove them.
Get-Event | Remove-Event

Now that we've cleaned up our runspace, let's clean up this post and review what we've learned:

Events are Easy

  • Events are Easy to create (New-Event)

  • Events are Easy to list (Get-Event)

  • Events are Easy to remove (Remove-Event)

  • Events are Easy to subscribe to (Register-EngineEvent)

  • Events are Easy on any object (Register-ObjectEvent)

Events are Easy!

Give them a try.

Eventually, you'll find events are excellent tools of the trade.


r/PowerShell • • Jan 20 '26

PowerShell Networking Commands Reference

115 Upvotes

Here’s a solid toolbox of Windows PowerShell commands used for network troubleshooting, with quick notes on what each one is good for.

I’ll try to group them by task so they are a little easier to remember.

1. Basic Connectivity & “Ping-Style” Tests

Test-Connection

PowerShell’s ping (ICMP echo) equivalent.

  • Quick ICMP test: Test-Connection 8.8.8.8

  • More detail (count, delay, etc.): Test-Connection -ComputerName 8.8.8.8 -Count 4 -Quiet

Test-NetConnection

More advanced tester: port check + traceroute + ping.

  • Simple ping-like test: Test-NetConnection google.com

  • Test specific TCP port (great for web, RDP, etc.): Test-NetConnection google.com -Port 443 Test-NetConnection server01 -Port 3389

  • Show route info: Test-NetConnection 8.8.8.8 -TraceRoute

2. IP Configuration & Adapters (PowerShell version of ipconfig)

Get-NetIPConfiguration

High-level view: similar to ipconfig /all but object-based.

Get-NetIPConfiguration
Get-NetIPConfiguration -Detailed

Get-NetIPAddress

Show IP addresses bound to interfaces.

Get-NetIPAddress
Get-NetIPAddress -InterfaceAlias "Ethernet"

New-NetIPAddress, Set-NetIPAddress, Remove-NetIPAddress

Create, change, or remove IPs (static configs).

New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.50 -PrefixLength 24 -DefaultGateway 192.168.1.1

Get-NetRoute

View routing table (PowerShell version of route print).

Get-NetRoute
Get-NetRoute -DestinationPrefix 0.0.0.0/0   # default routes

Get-NetAdapter

See physical/logical adapters and status.

Get-NetAdapter
Get-NetAdapter -Name "Ethernet" | Format-List

Restart-NetAdapter

Bounce an interface (like disabling/enabling in GUI).

Restart-NetAdapter -Name "Ethernet" -Confirm:$false

3. DNS & Name Resolution

Resolve-DnsName

PowerShell replacement for nslookup.

Resolve-DnsName google.com
Resolve-DnsName google.com -Type MX
Resolve-DnsName 8.8.8.8 -Type PTR   # reverse lookup

Get-DnsClientServerAddress

See what DNS servers a client is using.

Get-DnsClientServerAddress
Get-DnsClientServerAddress -InterfaceAlias "Ethernet"

Get-DnsClientCache / Clear-DnsClientCache

View and flush the local DNS resolver cache.

Get-DnsClientCache
Clear-DnsClientCache

4. Connections, Ports & Sessions (PowerShell replacement for netstat)

Get-NetTCPConnection

View active TCP sessions and listening ports.

Get-NetTCPConnection
Get-NetTCPConnection -State Listen
Get-NetTCPConnection -RemotePort 443

Get-NetUDPEndpoint

Show UDP listeners/endpoints.

Get-NetUDPEndpoint

Combine with process info:

Get-NetTCPConnection | Group-Object -Property State
Get-NetTCPConnection | Where-Object { $_.LocalPort -eq 3389 }

5. Neighbor / ARP & MAC-Level Stuff

Get-NetNeighbor

PowerShell view of ARP/neighbor table (IPv4 & IPv6).

Get-NetNeighbor
Get-NetNeighbor -State Reachable

Get-NetAdapterStatistics

Per-NIC counters: bytes, packets, errors, discards.

Get-NetAdapterStatistics

Great for spotting errors on a specific NIC.

6. Network Profile, Firewall & Sharing

Get-NetConnectionProfile

Shows network profile (Domain / Private / Public).

Get-NetConnectionProfile

Useful when firewall is tight on “Public” and breaking things.

Get-NetFirewallProfile / Set-NetFirewallProfile

Check and adjust firewall profiles.

Get-NetFirewallProfile

Get-NetFirewallRule

See firewall rules that might be blocking a port/app.

Get-NetFirewallRule
Get-NetFirewallRule -DisplayName "*Remote Desktop*"

7. Wireless & Network Diagnostics (using PowerShell to drive other tools)

These are not native PowerShell cmdlets, but you commonly call them from PowerShell:

netsh wlan

Wi-Fi profiles, signal, etc.

netsh wlan show interfaces
netsh wlan show networks mode=bssid

ipconfig / tracert / arp / nslookup

Classic commands, still very useful, and you can wrap/parse them in PowerShell:

ipconfig /all
tracert 8.8.8.8
arp -a
nslookup google.com

8. Advanced / Event-Based Troubleshooting

These are more advanced, but good to know they exist.

New-NetEventSession, Add-NetEventProvider, Start-NetEventSession

Used to trace and capture network events (more advanced, similar to using ETW).

New-NetEventSession -Name "NetTrace"
# then add providers, start, stop, etc.

9. Useful Patterns Techs Actually Use

A few patterns you might find yourself using a lot:

Check if a host is reachable and port open:

Test-NetConnection server01 -Port 445

See what’s listening on a port:

Get-NetTCPConnection -LocalPort 3389

Quick “PowerShell ipconfig+route+DNS” snapshot:

Get-NetIPConfiguration
Get-NetRoute
Get-DnsClientServerAddress

Look for NIC errors:

Get-NetAdapterStatistics | Format-Table Name, ReceivedErrors, OutboundErrors

r/PowerShell • • Mar 08 '23

PowerGPT: Run commands using natural language using GPT model

115 Upvotes

https://github.com/ouromoros/PowerGPT

Hi, I wrote a PowerShell module that offers a quick way to utilize power of GPT model to assist performing tasks in PowerShell. Basically it works like this:

$ PowerGPT "list all files in current folder with created date"
Will execute script:
-----
Get-ChildItem | Select-Object Name, CreationTime
-----

The functions and code are a little unpolished now but I already find it really handy to use. I would love to hear your opinions on it. Welcome to have a try :)


r/PowerShell • • Nov 08 '21

Script Sharing I did a thing! (Windows Admin Module/Repo)

115 Upvotes

I was able to finally get all of my go to Windows/AD Ops Scripts into a github repo to share with the community.

History

A few years ago I took the challenge to perform all daily duties from a remote shell. Everytime that I (or a teammate) had to logon via RDP to look at something, we added that scenario to a backlog and slowly added to the list. Some commands are actually wrappers for regular cmd commands (netstat, tasksch, etc.).

Behind the Scenes

I've worked with and created modules before, but I've never pushed one to the powershellgallery. My github repo is setup to Run PSScriptAnalyzer against any commit and upon the creation of a release, it will publish the module to powershellgallery.

Useful/Interesting Commands

Get-List - Paste a list into your shell, instead of having to call a .txt file. Easily my most used command working with lists of servers or users all the time.

Get-Table - Paste a table from excel into your shell and store as a pscustomobject.

Compare-Servers - Useful for troubleshooting why something works on one server and not the other.

Get-GPResult - Get an RSOP report from a remote machine even if you've never logged on to it.

Get-PortCertificate - stolen from someone else but useful for identifying machines where you only have an IP and no reverse DNS record.

Get-Htop - Get performance info via graph for remote machines.

Get-SChannelInfo - Useful for hunting down the info that IISCrypto will give you.

Room for improvement

  • No help files yet.... will get there.

  • Missing a few commands that I need to hunt down... Compare-ADUser, etc.

Links

Github Repo

PowerShell Gallery Package


r/PowerShell • • Jan 07 '21

Information Basics of Powershell For Pentesters - TryHackMe Hacking with Powershell P1

115 Upvotes

In this video walkthrough, we demonstrated the basics of PowerShell scripting language and how to conduct basic enumeration for the windows system. The machine is part of tryhackme room: hacking with PowerShell

video is here


r/PowerShell • • Jun 27 '20

Oneshot: easily transfer files to and from your computer and any browser. Features: HTTPS (including self-signing certificates), authentication, archiving (.zip & .tar.gz), mDNS (bonjour), a flexible CGI environment with default headers and more!

115 Upvotes

I just released v1.0.0 of my latest project, oneshot which was born out of frustration of all the hoops I sometimes had to jump through sometimes to do a simple file transfer.

I'd love to get your feedback on the project or answer any questions you may have. Thanks!

Link to project

Edit: Wow it seems people like this a lot more than I expected; thank you for the kind words and the reddit awards! If there are any bugs you encounter or features you'd like to possibly see added please feel free to send me a message or open an issue on Github.


r/PowerShell • • Mar 28 '20

Information Back to Basics: Understanding the PowerShell Switch Statement

115 Upvotes

Hello fellow scripters, June Castillote just wrote a shiny new blog post you may enjoy on the ATA blog.

Summary: The PowerShell switch statement has more capability than most think. Learn all about this versatile statement in this article.

https://adamtheautomator.com/powershell-switch


r/PowerShell • • Mar 13 '20

Run PowerShell scripts as Windows service

115 Upvotes

Hi all! I just open-sourced a PSScriptsService on GitHub that lets you run scheduled PowerShell scripts as Windows service.

It creates thread timer for each found script in specified directories and passes the current utc time:

myCommand.Parameters.Add(new CommandParameter("Automated", true)); myCommand.Parameters.Add(new CommandParameter("CurrentDateTimeUtc", DateTime.UtcNow.ToString("o")));

which you can retrieve on script side this way:

 [CmdletBinding()]
    param (
        [switch]$Automated,
        [string]$CurrentDateTime
    )

    if($CurrentDateTime) {
        [datetime]$CurrentDateTime = [datetime]::parseexact($CurrentDateTime, 'dd/MM/yyyy HH:mm:ss', $null)
    }

    Write-Host "Automated: $Automated" -ForegroundColor Green
    Write-Host "CurrentDateTime: $CurrentDateTime" -ForegroundColor Green

Schedule logic should be managed into the script, as it was an original requirement.

Let me know if you have any proposal on how to make this simple program better, more flexible and useful.


r/PowerShell • • Oct 15 '15

PowerShell Basic Cheat Sheet

Thumbnail ramblingcookiemonster.github.io
115 Upvotes

r/PowerShell • • Oct 06 '20

Script Sharing The Syntax Difference Between Python and PowerShell

Thumbnail
techcommunity.microsoft.com
114 Upvotes

r/PowerShell • • Oct 23 '19

New PowerShell Version - v7.0.0-preview.5 Release of PowerShell Core

Thumbnail
github.com
114 Upvotes

r/PowerShell • • Aug 11 '19

Daily Post KevMar: Everything you wanted to know about the if statement

Thumbnail
powershellexplained.com
114 Upvotes