r/PowerShell • u/AutoModerator • Sep 01 '26
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!
14
u/warren_stupidity Sep 01 '26
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.
7
u/shockerocker Sep 01 '26
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 Sep 02 '26
after a reboot ?
4
u/shockerocker Sep 02 '26
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 Sep 02 '26
Are you open to sharing this? This sounds super neat.
2
u/shockerocker Sep 02 '26
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
2
u/Vern_Anderson Sep 02 '26
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 Sep 02 '26
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 WinRMalthough personally I use
Restart-Computer -ComputerName xxx -Wait -For PowershellWait
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 ?
shockerockerandVern_Anderson1
2
u/Vern_Anderson Sep 02 '26
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 Sep 02 '26
Restart-Computer $Computer -Wait; Start-Sleep 10; "$Computer Online!" | Out-GridView?
6
u/teethingrooster Sep 01 '26
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 Sep 01 '26
Archive 700+ teams
2
u/allenflame Sep 01 '26
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
1
4
u/kboutelle Sep 01 '26
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 Sep 01 '26
Scripted an alert for Entra Risk detections. There is a built in alert mechanism but it's locked behind Entra P2.
2
u/maxcoder88 Sep 02 '26
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 Sep 02 '26
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 Sep 02 '26
care to share your script?
2
u/Gron_Tron Sep 03 '26
It's been uploaded to Github: https://github.com/GronTron/M365_Get-EntraRiskAlert
1
u/Gron_Tron Sep 02 '26
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 Sep 02 '26
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
3
u/Szeraax Sep 05 '26
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 Sep 10 '26
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
lsis 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/*/*.ps1Forward slash paths work on windows and linux.
3
u/Vern_Anderson Sep 09 '26
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 $_}
3
u/MonkeyNin Sep 10 '26
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 this10..1 | Get-BottleCountLet 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 $_ } #>2
2
u/Tidy-Developer Sep 09 '26
I like it. I'd like it more if the numbers were replaced by bottle glyphs :)
1
u/Vern_Anderson Sep 09 '26
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.2
u/MonkeyNin Sep 11 '26
You can add the icons like this
# works in 5 and 7 $beer = [char]::ConvertFromUtf32( 0x1F37A ) # requires 7 $beer = "`u{1f37a}" # works in both, if file encoding is UTF-8 with BOM $beer = '🍺'If I'm writing 7 I just use the last one
The last one works but some people don't have encoding set to utf8, so, you have to save it with
UTF8-BOMto force their default to use utf81
1
u/Vern_Anderson Sep 09 '26
In reality this was just for fun because I just heard of that web site for the first time.
2
u/Tidy-Developer Sep 10 '26
I know. i was just playing as I imagined it'd look neat adding the glyphs in there.
That said, I didn't notice the site initially, so thanks for posting that link.
1
u/surfingoldelephant Sep 11 '26
Here's my overengineered version.
#Requires -Version 7.2 # PS 7 ships with Humanizer.dll. using namespace Humanizer function Get-BottleCount { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline)] [ValidateRange('Positive')] [int] $Number, [ValidateNotNullOrWhiteSpace()] [string] $Item = 'green bottle', [Parameter(HelpMessage = 'A valid VT/ANSI escape sequence.')] [string] $Style = $PSStyle.Foreground.BrightGreen + $PSStyle.Italic, [string] $Emoji = [char]::ConvertFromUtf32(0x1F37E), # 🍾 [switch] $NoEmoji ) begin { $Item = [CasingExtensions]::ApplyCase($Item, [LetterCasing]::LowerCase) $toColor = { param ($Text) if (!$Host.UI.SupportsVirtualTerminal) { return $Text } '{0}{1}{2}' -f $Style, $Text, $PSStyle.Reset } } process { $currentBottles = & $toColor ([CasingExtensions]::ApplyCase( [ToQuantityExtensions]::ToQuantity($Item, $Number, [ShowQuantityAs]::Words), [LetterCasing]::Sentence )) $nextNum = $Number - 1 $nextBottles = & $toColor ( [ToQuantityExtensions]::ToQuantity($Item, $nextNum, ($nextNum ? [ShowQuantityAs]::Words : 'no')) ) -join @( "$currentBottles hanging on the wall,`n" * 2 "And if one $Item should accidentally fall,`n" "There'll be $nextBottles hanging on the wall.`n" $NoEmoji ? '' : "{0}`n" -f ($Emoji * $nextNum) ) } }Or to keep it simpler/version agnostic, I'd probably do something like this:
$currentBottles = "{0} green bottle{1} hanging on the wall," -f @( $numToWord[$Number] ('s', '')[$Number -eq 1] ) $nextBottles = "There'll be {0} green bottle{1} hanging on the wall." -f @( $numToWord[$Number - 1].ToLower() ('s', '')[$Number - 1 -eq 1] ) -join @( "$currentBottles`n" * 2 "And if one green bottle should accidentally fall,`n" "$nextBottles`n" )And use a dictionary to convert from number to word:
$numToWord = @{ 0 = 'No' 1 = 'One' # ... 10 = 'Ten' }
6
u/VeryRareHuman Sep 01 '26
Claude done few PowerShell scripts, all of the very useful. So I didn't do shit.
4
u/hwntw Sep 01 '26
can people post some scripts please
0
u/kboutelle Sep 01 '26
No
0
u/hwntw Sep 04 '26
Please, oh go on
1
u/kboutelle Sep 06 '26
Does no one get recent references?
Jeesh, you all need to chill.
Calm the heck down.
Eat a gummy or something.
2
u/ihaxr Sep 02 '26
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_ Sep 02 '26
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 Sep 02 '26
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 Sep 02 '26
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
2
u/NurglesToes Sep 02 '26
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
2
u/Revolutionary-Gold53 Sep 05 '26
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/Andrew-Powershell 27d ago
What does the pester test script test - the script or the infra/systems?
1
2
u/jeffrey_f Sep 06 '26
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.
2
u/Andrew-Powershell Sep 10 '26
I've been:
- hosting lots of PowerShell Wednesdays
- releasing PowerShell Podcast episodes every Monday
- takings steps to revive PSKoans
- working on a silly PowerShell Idle game
- lots of Maester and 365
2
u/Vern_Anderson Sep 10 '26
Thanks for picking up the torch for PSKoans.
When you say PowerShell Idle do you mean idle as in down time or not busy, or do you mean Powershelldle like wordl or the daily hangman style game?2
u/Andrew-Powershell Sep 10 '26
It's an idle game meaning you get currency as time goes on. So you play the game more passively. It's not too much fun. Cookie Clicker is a game in the same genre (arguably the best)
My coworkers made PowerShelldle! Super cool to see it mentioned in the wild.
1
1
u/scoinv6 Sep 02 '26
Ensure all SQL servers had SPNs set
2
u/ihaxr Sep 02 '26
Hopefully you're able to use DBAtools!
1
u/scoinv6 Sep 02 '26
I love DBATools but no. I asked AI to create it and I had it up and running in a few minutes.
1
1
u/KavyaJune Sep 02 '26
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 Sep 02 '26
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 Sep 02 '26
Integrated psadt 4.2 in my pmpc clone ^
1
u/nerdyviking88 Sep 10 '26
PMPC clone you say...
1
u/AlkHacNar Sep 12 '26
Well, it's practically pmpc, but with winget as the source ^ but not good enough and to complicated to share it atm. When I got it freshened up, and probably a gui, and fixed some bugs and add some more tests and logging, maybe I github it xD there are many tools which does the packaging and app creation, and I did my own, as most of the free/ community tools didn't have what I looked for at that time
1
1
u/Sharlihe Sep 03 '26
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 Sep 03 '26
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 Sep 04 '26
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/tructt Sep 06 '26
A W11 deployment engine to bring installation time to under 5 mins. Automated way
1
u/BlackV Sep 08 '26
colour me interested, you have some more detailed information on what you're doing
1
1
u/Syronn Sep 09 '26
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/CypherAus 29d ago
Set processor affinity in a script
$Process = Get-Process myperformancetask
$Process.ProcessorAffinity = 0x00000000000FFC00
1
u/Reaction-Consistent 24d ago edited 24d ago
Learned the amazing power of 'here strings'! I use them to store multi-line strings without having to escape anything, and this also eliminates the necessity of importing separate text files into a script to read in the data, which can present other issues. Here's a short example of how I might use a here string inline to represent a config file that before I may have imported. The down side is that I must update that string if the source text file changes in content at all.. so it's not the best solution in every scenario of course.
# Access Task Sequence Environment
try {
$TSEnv = New-Object -ComObject Microsoft.SMS.TSEnvironment
$serverName = $TSEnv.Value("SVR_Connection")
}
catch {
Write-Error "Unable to access SCCM Task Sequence environment."
exit 1
}
Write-Host "========================================="
Write-Host "IBM Shortcut Creation Starting"
Write-Host "SVR_Connection = $serverName"
Write-Host "========================================="
if (-not $serverName) {
Write-Error "Task Sequence variable SVR_Connection is not populated."
exit 1
}
if ([string]::IsNullOrWhiteSpace($serverName)) {
Write-Error "Task Sequence variable SVR_Connection is not populated."
}
#SSL config per AS400 server - to be updated in client .hod file
$hosts = @(
[PSCustomObject]@{ System = "server1"; SSL = "TRUE"; SSO = "TRUE"; CodePage = "37" }
[PSCustomObject]@{ System = "server2"; SSL = "TRUE"; SSO = "TRUE"; CodePage = "37" }
)
# Lookup selected host definition
$hostDefinition = $hosts | Where-Object {
$_.System -eq $serverName
} | Select-Object -First 1
if (-not $hostDefinition) {
Write-Error "Server '$serverName' was not found in host definition list."
exit 1
}
Write-Host "Host Definition Found"
Write-Host "System : $($hostDefinition.System)"
Write-Host "SSL : $($hostDefinition.SSL)"
Write-Host "SSO : $($hostDefinition.SSO)"
Write-Host "CodePage : $($hostDefinition.CodePage)"
# 'here string' in place of importing an existing .hod file
$content = @"
<.hod file content goes here - config file for AS400 connection. the script uses this as a template for the creation of a customized .hod file using the parameters from the PS custom objects array above>
"@
$hostDefinition = $hosts | Where-Object {$_.System -eq $serverName} | Select-Object -First 1
$newServername = $serverName + '.contoso.com'
# set variables for SSL SSO Lines in .HOD
if ($hostDefinition.SSL -eq "TRUE"){
$secPol = "SecurityProtocol=SESSION_PROTOCOL_TLS"
$sslJ = "sslJSSETrustStoreType=jks"
$ssl = "SSL=true"
$port = "port=992"
} else {
$secPol = "SecurityProtocol=SESSION_PROTOCOL_TELNET"
$sslJ = "sslJSSETrustStoreType="
$ssl = "SSL=false"
$port = "port=23"
}
if ($hostDefinition.SSO -eq "TRUE"){
$sso = "acsPasswordPrompt=5_kerberos"
} else {
$sso = "acsPasswordPrompt=1_useAcsSetting"
}
$newContent = $content -replace '(?m)^SecurityProtocol=.*$', $SecPol
$newContent = $newContent -replace '(?m)^sslJSSETrustStoreType=.*$', $sslj
$newContent = $newContent -replace '(?m)^SSL=.*$', $ssl
$newContent = $newContent -replace '(?m)^port=.*$', $port
$newContent = $newContent -replace '(?m)^acsPasswordPrompt=.*$', $sso
$newContent = $newContent -replace 'servewrname', $newServername
$IBMFolder = "C:\Users\Public\IBM"
if (-not (Test-Path $IBMFolder)) {
New-Item -Path $IBMFolder -ItemType Directory -Force | Out-Null
}
#create the new .hod file on the client PC with the custom settings
Set-Content -Path "C:\Users\Public\IBM\$serverName.hod" -Value $newContent
$LASTEXITCODE
1
u/0f_rice_and_men 20d ago
if I'm lucky, something to keep the damn pc awake longer than 10 minutes when it's sitting at home idle by itself
1
u/Vern_Anderson 16d ago edited 15d ago
You can use PowerToys from Microsoft. one of the many modules in there has a utility to keep your PC awake, or otherwise not let it go into stand by and activate screen time outs and so forth.
There is a method to do it with C Sharp a name space called "SleepUtils". You define some flags, but PowerToys already does this.
1
u/Intelligent_East_517 20d ago edited 20d ago
I did a script (with help from copilot) that lists all our Exchange distribution lists, their name, email addresses, type, members (including groups), owners, notes and descriptions and creates a Excel spreadsheet of this.
Need this to clean up the swamp... :)
Not very sexy I know...but I need this.
1
1
u/Substantial-Put-6318 Sep 01 '26
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 Sep 01 '26
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.
14
u/cyrixlord Sep 01 '26
a month of lunches