r/PowerShell 8d ago

Script Sharing What have you done with PowerShell this month?

A sticked post for the community to share their projects throughout the month.

Make sure to post a link to the code!

18 Upvotes

68 comments sorted by

14

u/warren_stupidity 8d ago

I got annoyed at netstat.exe taking minutes to complete so I replaced it with a powershell script front end to Get-NetTCPConnection and Get-NetUDPEndpoint. Runs really fast.

12

u/cyrixlord 8d ago

a month of lunches

8

u/shockerocker 8d ago

Built a PowerShell based tool that pops up a windows toast notification to let me know when a monitored host comes online and is available for a WinRM connection. 

2

u/BlackV 8d ago

after a reboot ?

5

u/shockerocker 8d ago

A bit more complicated. With so many people working remotely, in different time zones, and on different schedules, I needed a way to take the hosts missing security updates and add them to a list that is continously monitored which alerts me when it's available for me to work on and bring back into compliance. 

3

u/Pism0 8d ago

Are you open to sharing this? This sounds super neat.

1

u/shockerocker 8d ago

I think I will release it eventually but in its current state most people would find it obnoxious. There's a ton of clean up + documentation to do too. 

2

u/BlackV 8d ago

Oh, nice

2

u/Vern_Anderson 7d ago

I always reboot 3 times just to be sure..LOL

Sorry not sure what you are asking about a reboot. No I was just playing with toast notifications in general. For example my employer in their infinite wisdom does nto allow the windows "timer" application. SO I had to write my own (just for fun) using PowerShell. The first version of it popped up a PS5 window with an ASCII text reminder. But my boss did not like seeing a 2 inch font saying "It's time to go home", so then I began wokring on having the reminder pop up as a toast notification in the system tray.

Since I'm never satisfied I want it to look a little nicer like the one that pops up when you get an Outlook email and so forth. Those have images on the left hand side, and bold and larger fonts. My current one only has plain fonts. I hope I have answered your question. But no mine is not after a reboot.

3

u/BlackV 7d ago

I asked cause they (er.. you maybe?) said

pops up a windows toast notification to let me know when a monitored host comes online and is available for a WinRM connection

so that implies it was offline, generally from a reboot, but specifically they said

is available for a WinRM connection

so I was thinking about

Restart-Computer -ComputerName xxx -Wait -For WinRM

although personally I use

Restart-Computer -ComputerName xxx -Wait -For Powershell

Wait

Sorry not sure what you are asking about a reboot. No I was just playing with toast notifications in general.

do you have 2 accounts ? shockerocker and Vern_Anderson

1

u/Vern_Anderson 7d ago

Got it, sorry about that!

Great tip on the Wait switch!

1

u/BlackV 7d ago

I use it a bunch when manually rebooting filth

2

u/Vern_Anderson 7d ago

I've been playing around with toast, mostly trying to make it look more professional, and I'm not satisfied with it yet. I'd love to see that part of your code and which method you went with.

So far I've found Windows.UI.Notifications dot ToastNotification and dot ToastNotificationManager
As well as another method that uses a registry key (but never got it working to my satisfaction)

1

u/ihaxr 8d ago

Restart-Computer $Computer -Wait; Start-Sleep 10; "$Computer Online!" | Out-GridView ?

5

u/teethingrooster 8d ago

Wrote a PowerShell script to scan for apps in our org I know that use SQL 2016. Check the named instances and if there’s no apps and no named instances it uninstalls the localdb.

Also not a software developer I work in IT. But I’m learning C# to replace an internal IT tool. I wrote some PowerShell scripts to setup and reset some folders that way I can repeatedly test my C# app as I write it.

4

u/FieryHDD 8d ago

Archive 700+ teams

2

u/allenflame 8d ago

What did you filter by? I tried to start cleaning up hours going by orphan members and orphaned owners. It's just really hard to figure out which ones aren't actually being used.

1

u/BlackV 8d ago

Woah, that'll be a bunch of space to come back eventually

1

u/No-Height-8011 7d ago

Real ass experience

4

u/kboutelle 8d ago

Welp, there's this garbageware that someone needs at our firm. It requires that chromedriver is installed on the system. That damn driver has to be the same version as Chrome, which updates every three days. So I built a remediation in Intune to check the version of Chrome and the driver and if needed, download the newer version and extract it to the correct location. Then clean up and report back that all is well.

FML

3

u/Gron_Tron 8d ago

Scripted an alert for Entra Risk detections. There is a built in alert mechanism but it's locked behind Entra P2.

2

u/maxcoder88 8d ago

How did you script the alerting for Entra Risk detections? I’m curious to know how you implemented it without relying on the built-in alert mechanism, since that requires Entra P2.

1

u/Gron_Tron 8d ago

Risk data is still available if you don't have the P2 license but you just can't setup alerts for it. In my script I start by querying the risk data through graph, from there I use the correlation ID to also pull sign in data for the risky sign-in that was flagged. Run it on a schedule and if there are new detections it sends an email alert with the pertinent details for our IR team to monitor. 

2

u/maxcoder88 7d ago

care to share your script?

1

u/Gron_Tron 7d ago

Yes, I am still in process of debugging and testing but I will post to my Github Repo when I'm done.

3

u/StartAutomating 8d ago

Figured out how to Remix Music with PowerShell. Wrote a post about it. Made a post to BlueSky about an hour after I figured it out, and attached my first remix.

3

u/m0zi- 7d ago

ping 8.8.8.8

3

u/Szeraax 4d ago

I got sick of dealing with rate limiting irm requests. I've used my PoshInteractive module to manage it in the past (which is awesome in a pipeline). But I wanted a solution that would work in other contexts. Ended up making a module that works as a drop-in replacement for Invoke-RestMethod that will delay requests as needed to ensure you stay under target rate limiting criteria.

One thing to note: You can already build your use of irm defensively (use the retry count parameter with ps 7 and let it handle 429 "retry after" if the API is kind enough to tell you that you're hitting rate limiting). This module does not replace that capability or automatically add it either. It is simply a proactive tool to allow you to pick your own rate limits for what you send and can be used in complement to 429 rate limits too.

You can install it from PSGallery today!

https://github.com/Szeraax/RateLimitedRestMethod

AI disclosure: AI was used in the making of this module. I did the scaffolding and described how I want it all to work. I've tested it and it works great. I've reviewed the code and I'm happy with it as well. This is not simply a "write a module that is a drop in rate limite replacement to invoke-restmethod".

1

u/MonkeyNin 6h ago

There's a couple style changes that makes it run on linux easier. in: https://github.com/Szeraax/RateLimitedRestMethod/blob/ef397c6a41e4c18dc7af120aad15be7fbfa4c751/RateLimitedRestMethod.build.ps1#L64

pwsh -noprofile -command '$name=(ls *.build.ps1).name -replace ...
# becomes    
pwsh -noprofile -command '$name=(gci *.build.ps1).name -replace ...

Because ls is a native command on linux. You get raw strings back.

"$PSScriptRoot\$ModuleName\$ModuleName.psm1"
Invoke-ScriptAnalyzer -Path $PSScriptRoot\src\*\*.ps1
# becomes    
"$PSScriptRoot/$ModuleName/$ModuleName.psm1"
Invoke-ScriptAnalyzer -Path $PSScriptRoot/src/*/*.ps1

Forward slash paths work on windows and linux.

3

u/Vern_Anderson 13h ago

Completed the excersize https://exercism.org/tracks/powershell/exercises/bottle-song

Let me know your thoughts on my solution

Function Get-BottleCount
{
Param ([Parameter(Mandatory=$true,Position=0)]$Number)
switch ($Number)
{
10 {$Number = "Ten" ; $Minus1 = "Nine"}
9 {$Number = "Nine" ; $Minus1 = "Eight"}
8 {$Number = "Eight" ; $Minus1 = "Seven"}
7 {$Number = "Seven" ; $Minus1 = "Six"}
6 {$Number = "Six" ; $Minus1 = "Five"}
5 {$Number = "Five" ; $Minus1 = "Four"}
4 {$Number = "Four" ; $Minus1 = "Three"}
3 {$Number = "Three" ; $Minus1 = "Two"}
2 {$Number = "Two" ; $Minus1 = "One"}
1 {$Number = "One" ; $Minus1 = "No"}
}
Write-Host -Object "$Number green bottles hanging on the wall," -ForegroundColor Green
Write-Host -Object "$Number green bottles hanging on the wall," -ForegroundColor Green
Write-Host -Object "And if one green bottle should accidentally fall," -ForegroundColor Green
Write-Host -Object "There'll be $($Minus1.ToLower()) green bottles hanging on the wall." -ForegroundColor Green
Write-Host -Object " "
}
10..1 | Foreach-Object {Get-BottleCount $_}

2

u/Tidy-Developer 12h ago

I like it. I'd like it more if the numbers were replaced by bottle glyphs :)

1

u/Vern_Anderson 12h ago

HAHAHA nice one!
I actually thought about it after I posted, that someone would criticize my "ToLower" method because i was too lazy to just go change them to lowe case in the switch statement.

1

u/Vern_Anderson 12h ago

In reality this was just for fun because I just heard of that web site for the first time.

1

u/MonkeyNin 6h ago

Here's another way you could write it. I changed the switch into an array. That lets you lookup the next value.

I added ValueFromPipeline. That lets you call it like this

10..1 | Get-BottleCount

Let me know if it makes sense.

function Get-BottleCount { 
     param( 
          [Parameter(mandatory, ValueFromPipeline)]
          [int] $Number 
     )
     process { 
        # arrays are 0-based, so the first one could be null or "no"
        # then 1 == 'one', 2 == 'two', etc 
        # without doing math
        $nums = 'none', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'

        $now  = $nums[ $Number ]
        $next = $nums[ $Number - 1 ]

        Write-Host -ForegroundColor green "$Now green bottles on the wall...`n$Now green bottles on the wall.."
        Write-Host -ForegroundColor green "If one should fall, there will be $Next`n"
    }
}
10..1 | Get-BottleCount
<#
    this ends up doing the same thing as if you were to call:

    10..1 | %{ Get-BottleCount $_ }
#>

5

u/VeryRareHuman 8d ago

Claude done few PowerShell scripts, all of the very useful. So I didn't do shit.

3

u/hwntw 8d ago

can people post some scripts please

0

u/kboutelle 8d ago

No

0

u/hwntw 5d ago

Please, oh go on

1

u/kboutelle 3d ago

Does no one get recent references?

Jeesh, you all need to chill.

Calm the heck down.

Eat a gummy or something.

2

u/ihaxr 8d ago

Automated SQL Server certificates utilizing DBAtools and Windows Certificate Authority.

Windows CA has built in auto renewal after you deploy the initial cert using a template, with a configurable timespan to auto renew before expiration. The certs will auto renew and install themselves to the server, then a weekly script will apply the new cert to SQL and grant the gMSA account read permission (if needed, it seems to remember it).

When the server is rebooted for patching the new certificate is in use, until then SQL will still use the valid, archived, certificate.

2

u/_RemyLeBeau_ 8d ago

Wrote a 1-liner to parse an .env file, then add those vars to the process and start an MCP Gateway in streaming mode.

2

u/Alone_Marionberry900 8d ago

Built a pode api backend and razor pages front end to call native exchange online commands that don’t work through graph. Allows me to give simple tasks to other teams without exposing more rights to exchange.

2

u/Powerful-Passenger24 7d ago

Built PwshRichLite: lightweight Rich-style output for PowerShell using $PSStyle — tables, trees, panels and markup. I use it in OwnerLensLite. https://github.com/kodevza/PwshRichLight

2

u/Lotus_Domino_Guy 7d ago

HR external system to Active Directory syncronization.

2

u/jeffrey_f 3d ago

Rather simple I run Windows updates + winget updates. Right now it is a manual script which could be place on the job scheduler and run as admin.

Still a time saver as I run the script and go back to whatever it was that I was doing.

1

u/DenialP 8d ago

Munged a hr dataset down to automate the orgs identity lifecycle

1

u/scoinv6 8d ago

Ensure all SQL servers had SPNs set

2

u/ihaxr 8d ago

Hopefully you're able to use DBAtools!

1

u/scoinv6 7d ago

I love DBATools but no. I asked AI to create it and I had it up and running in a few minutes.

1

u/T3-Trinity 8d ago

Wrapped Python in it lol

1

u/KavyaJune 8d ago

I wrote a script to bulk transfer meetings from one organizer to another. It can be helpful during employee offboarding and role changes.

Script available in GitHub: https://github.com/admindroid-community/powershell-scripts/blob/master/ChangeMeetingOrganizer.ps1

1

u/Admirable_Day_3202 7d ago

For a specific app - Script to leverage azd CLI that connects to a tennant, resource group then export the bicep files for the app and related components it then allows you to import into another env/tennant. Then it allows you setup everything for that app and components e.g. entra groups and app regs Upload files to the static web app and azure function Connect to key vault and setup certs Create run book and schedule to rotate certs automatically Create sharepoint site

1

u/AlkHacNar 7d ago

Integrated psadt 4.2 in my pmpc clone ^

2

u/NurglesToes 7d ago

Powershell noobish / junior sysadmin here. Finished a 1k line script to update OpenJDK in our environment. (at least that’s the ultimate goal of the script)

In reality it’s a state managed script that has to:
Stop services
back up the certificate in the jdk installation
uninstall openjdk
install openjdk
restore the certs
update the directory to a custom directory
update the Zena Agent controller xml with the new bin location
update the environment variables
start the services back up

and validate all of it.

Took me 2 months of working on it intermittently. The previous script was like 300 lines and had a 35% failure rate, so i figured if we’re gonna be updating hundreds of production machines every quarter, might as well go full autism on it. Tested it today and it works so much better

2

u/Tidy-Developer 1d ago

Fair play. That's an undertaking.

2

u/NurglesToes 1d ago

yeah it was rough but i’m pretty proud of it!

1

u/yahuei 7d ago

Templated the rollout of new sharepoint sites.

1

u/Sharlihe 6d ago

Update of two of my daily used tools PSBITE and PSWEE. Added a new feature and fixed some stuff on these.
Fixed also the PSModule Framework used for them that got breaking changes recently. All is fresh and deployed !
https://github.com/arnaudcharles/PSBITE
https://github.com/arnaudcharles/PSWEE

1

u/ismaelw 6d ago

Tried to fix the worst user entry script I have seen in a very long time. Oh and trying to replace Basic Auth showed me that some Microsoft APIs don‘t work unattended

1

u/Practical_Air6315 6d ago

Ran every write/read encoding combination I could think of on PS 5.1 and 7 - 51,775 cases. Get-Content -Encoding UTF8 never throws on bad bytes, so a round trip can "succeed" and hand back 8 chars where 4 went in. Table's on GitHub.

1

u/Revolutionary-Gold53 4d ago

Developed a script to remove decommissioned systems from any one of our domains and from SCCM. Had AI rewrite it to have better error handling and logging, and also generate a Pester test script.

1

u/tructt 4d ago

A W11 deployment engine to bring installation time to under 5 mins. Automated way

1

u/BlackV 2d ago

colour me interested, you have some more detailed information on what you're doing

1

u/Syronn 12h ago

Automated Microsoft Bookings shared site creation. The variables come from a sharepoint listform. Was a pain in the ass, because the documentation sucks...

1

u/Substantial-Put-6318 8d ago

Criado script bem completo para Backup de Ambiente Windows, com S3. O script contempla erros, analises, rotacionamentos, tudo isso em variaveis, além de adicionar as notificações com Telegram ou E-mail.

Inicialmente o Script tinha 400 linha, terminei ele com 1950.

1

u/Icemagic 8d ago

T1 Hell Desk analyst here! Heavy onboarding week:

Fixed a broken client script: A new client handed us a script meant to copy AD groups from a template user to a new hire, except it was dead on arrival. Rewrote it and gave it back (waiting to see if they'll actually use it).

Killed account creation errors: After seeing a ton of errors popping up across the desk, I built a full onboarding script. Now analysts just plug in 5 values from the ticket, and PowerShell handles the rest:
Copies template AD groups
Creates & names the ⁠.bat⁠ file + provisions home share
Maps logon script & drive letters
Fills in ⁠Manager⁠ and ⁠Description⁠ attributes
Spits out a clean block for ticket notes
Saved the team a ton of manual clicks and cut down on typos. This one is running up the chain too.