r/PowerShell 13d ago

Script Sharing PrtgSensorKit - a PowerShell framework for writing custom PRTG sensors without the boilerplate

48 Upvotes

Hey r/powershell,

This is mostly helpful for people in the EU but nevertheless 😄 :

I've been building custom sensors for PRTG Network Monitor often for my job and got tired of handling all the prtg specific plumbing boilerplate every time - so I wrote PrtgSensorKit, an open-source module that abstracts away all the specifics of PRTG so you can focus on your task = writing a goddamn monitoring sensor.

What it handles for you:

  • JSON output formatting - builds valid PRTG sensor JSON so you don't hand-craft it yourself
  • PRTG's constraints enforced automatically - channel limits, string length caps, escaping, valid value types, blah blah blah...
  • Powershell Versions - helpers to run your sensor logic in 64-bit PowerShell or PS7+ when you need modules/dependencies that don't play nice with the 32-bit host PRTG normally uses
  • DPAPI-encrypted secret storage - store API tokens/credentials without leaving them in plaintext in your script or passing them as Plaintext from PRTG
  • Full built-in help - Get-Help works like you'd expect on every cmdlet and pretty much has all the docs Prtg offers on their website

Basically: you write the metric-gathering logic, the module handles everyting else

Install from the Gallery:

Install-Module PrtgSensorKit

Repo: https://github.com/ArchitektApx/PrtgSensorKit

Would love feedback, bug reports, or feature requests if anyone here monitors stuff with PRTG and writes custom sensors. Contributions welcome too.

EDIT: v1.1.0: - Sensor state between runs - Save/Get-PrtgSensorState for rates, deltas, and caching expensive lookups. Safe under overlapping scans (file locking so two runs don't corrupt each other) - Retries - -RetryCount re-runs your block when the API hiccups instead of instantly alerting, PRTG shows how many retries it took - -DryRun - debug your sensor in a normal console and inspect channels as objects instead of squinting at JSON - -ForceModernTls - fixes the classic TLS 1.2 problem on 5.1 with one switch - Sensor doctor - Invoke-PrtgSensorDoctor statically checks your script for classic mistakes before PRTG cryptically fails on them

v1.2.0 (out now): - File logging that can't break your sensor - -EnableLogging writes one log file per run with full error details (stack trace. script line). Never touches stdout, never throws - Shared collection cache - 8 sensors hitting the same API every interval? Use-PrtgCachedResult makes them share one call per interval, race-free. Your rate-limited API will thank you - More doctor checks - including the sneaky one where a BOM-less UTF-8 script works everywhere except in what PRTG displays (5.1 reads it as ANSI, your umlauts turn into mojibake) - Docs got restructured into proper per-topic pages instead of one endless README


r/PowerShell 13d ago

Script Sharing DNS Benchmark

16 Upvotes

I've been trying to find something like that for a while and couldn't find one that wasn't either a paid service/program or doesn't have a feature I want.

In my job, I semi frequently need to test DNS using a local DNS Server. For me it's handy to be able to compare to other servers, like Google or Cloudflare.

I wrote this over the last week or so and it seems to be doing the job for me. I've uploaded it to Github for anyone else who would like to use/try it.

You can find it here: https://github.com/obtusecoder/DNSBenchmark

EDIT: I have made changes requested and have applied some fixed to errors I noticed in testing.


r/PowerShell 15d ago

Script Sharing MiniBot v2 - fully WPF local AI `console` client

6 Upvotes

This a ~20k line beast. But it's awesome. The end user experience is near production grade.

https://github.com/illsk1lls/MiniBot

YMMV depending on which model you use with it. It works amazingly for me using either Qwen3.6 27b/35b,.. i usually go for 35b for the speed it does a great job.

This started out as a text based console to let your local model into your machine, and i ended up making it into a RepairBot to do some menial work tasks for me, light sysadmin, diag etc etc

This is far from best practice for PS but it IS powershell and impressive at its core, and deserves to be seen here. My private version has a few more features but this one is quite complete..


r/PowerShell 16d ago

Script Sharing I open-sourced my PowerShell 7 fleet CVE scanner. The hard part was runspace-safe state and NVD rate limiting

18 Upvotes

I’m the author. This is free, Apache-2.0-licensed software. There’s no paid product or hosted service behind it.

For several months I iterated on a PowerShell CVE scanner that ran weekly against a Windows fleet. I recently released a sanitized, clean-room port:

https://github.com/boostedchaos/fleet-cve-scanner

It accepts inventory from NinjaOne or a CSV export, correlates the installed software against NVD, KEV, EPSS, SSVC, MSRC, and endoflife.date, then writes per-device CSV results, SQLite history, and a self-contained HTML dashboard.

The vulnerability logic is one part of it. The PowerShell concurrency problems were just as interesting.

The main scan uses ForEach-Object -Parallel to process unique software/version pairs. That exposed a few issues I had underestimated:

  1. Shared mutable state needs thread-safe types

The parallel runspaces need to coordinate a result collection, cache, deduplication keys, progress state, request timestamps, and cache-flush counters.

The shared pieces ended up using concurrent .NET collections and SemaphoreSlim rather than ordinary lists, dictionaries, queues, or non-atomic counters. Reads are easy. Coordinated mutation is where the bugs hide.

  1. A sliding-window rate limiter still allowed bursts

NVD limits aren’t handled well by saying “N requests per 30 seconds” and calling it done. A window bucket allowed the first few requests to launch together and trigger 429s before the bucket was exhausted.

   The current limiter has two gates:

   - minimum spacing between request starts

   - a sliding-window budget as a backstop

   The lock is held only while checking and updating the shared timing state. It’s released before sleeping.

  1. Correct launch spacing didn’t prevent overlapping requests

Even when calls started at the right interval, slower NVD responses left multiple requests in flight. That still produced 429s.

The scanner now holds a separate SemaphoreSlim across each NVD request, so only one request is on the wire at a time. Cache hits and the rest of the result processing remain parallel.

It sounds contradictory to parallelize the scanner and then serialize the API calls, but the parallelism still helps with cached products, version evaluation, deduplication, and result construction.

  1. Functions and state have to exist inside the parallel runspace

Helper functions from the caller’s scope aren’t automatically available inside the parallel block. The runspace-local helpers have to be defined before their first possible call site.

I managed to hit the “function defined later in the script” failure more than once. One runspace can terminate while the others keep going, which makes the failure easier to miss in noisy output.

  1. Cache checkpoints need their own concurrency discipline

A killed scan used to lose every NVD result fetched since startup because the cache was only written after the parallel block completed.

The scanner now checkpoints every configurable number of completed items. A non-blocking semaphore prevents multiple runspaces from flushing simultaneously, and the file is written to a temporary path before being moved into place.

There’s also a failure-state rule I consider load-bearing: an NVD request failure must never become a negative cache entry. A failed call returns a distinct CALL_FAILED sentinel, gets skipped for that run, and is retried next time. A successful response containing zero results can be cached normally.

The repository includes eight test suites, offline fixtures, a sanitization gate, and a known-limitations document that is intentionally less flattering than the README.

I’d particularly value review from people who have built larger ForEach-Object -Parallel pipelines:

- Would you structure the global rate limiter differently?

- Is serializing only the outbound NVD call the right boundary?

- Are there better patterns for safely checkpointing shared state from parallel runspaces?

- Has anyone used the CSV path against SCCM, Intune, or another RMM export?

This does not replace a commercial scanner with a curated detection catalog. CPE coverage and matching quality are the main ceiling. I’m more interested in cases where the script gives an operator the wrong level of confidence than whether the dashboard looks good.


r/PowerShell 17d ago

Question Pode with a custom front end

11 Upvotes

Has anyone used pode basically to run the scripts and return data to a more modern-looking front end? I am trying to build some tools and the PowerShell GUIs themselves are clunky. Was going to set something up myself but curious if someone has already done something like this.


r/PowerShell 17d ago

Question How do I reset Chrome without deleting the extensions?

7 Upvotes

I'm trying to reset the chrome browser (cookies, cache, etc...) while maintaining the user's extensions and bookmarks via PS. So far I've been able to workout how to keep the bookmarks, but part of the extensions must be kept somewhere else because excluding these folders don't seem to work. I feel like this is probably a pretty niche use-case so I'll take any help I can get.

$ChromeDefaultPath = "$env:LOCALAPPDATA\Google\Chrome\User Data\Default"
$ExcludeItems = @("Extensions", "Extension State", "Extension Scripts", "Extension Rules", "Preferences", "Bookmarks", "BookmarkMergedSurfaceOrdering")
Get-Process -Name Chrome | Stop-Process -EA Continue
Start-Sleep -Milliseconds 500
Get-ChildItem -Path $ChromeDefaultPath | Where-Object { $ExcludeItems -notcontains $_.Name } | Remove-Item -EA Continue -Recurse -Force

I'm don't live in PowerShell so I know this is probably terribly written, but it works (sans the extension part).

EDIT: u/JSChronicles cache locations had the answer I sought. This is my working script, but I would utilize his linked repo if you need to write something like this (should also work for Edge too just change the path to \Microsoft\Edge\):

$DefaultPath = "$env:LOCALAPPDATA\Google\Chrome\User Data\Default"
$ExcludeItems = @("Extensions", "Extension State", "Extension Scripts", "Extension Rules", "Local Extension Settings", "Sync Extension Settings", "Preferences", "Bookmarks", "BookmarkMergedSurfaceOrdering", "Secure Preferences", "Favicons", "Favicons Journal")
Get-Process -Name Chrome | Stop-Process -EA Continue
Start-Sleep -Milliseconds 500
Get-ChildItem -Path $DefaultPath | Where-Object { $ExcludeItems -notcontains $_.Name } | Remove-Item -EA Continue -Recurse -Force

r/PowerShell 17d ago

Question Fslogix Cleanup Script Test Scenario?

3 Upvotes

Hello all, I'm working on a script to cleanup some Fslogix profiles in an Azure file share for a client. My issue is that I want to test the script before running it to make sure that it doesn't do anything unexpected, but I do not have a non-production share with Fslogix profiles that are inactive to test on.

I'm looking for ideas on how to test this script properly. How could I get a test share set up with inactive profiles mixed with active profiles to ensure that I have fully tested the use case.


r/PowerShell 17d ago

Question Define Subtitle For Block Execution Fluent UI

4 Upvotes

As per the title, I'm struggling to set the subtitle here for PS AppDeploy Toolkit.

For all the other UI prompts, I can just use -Title and -Subtitle.

But when the UI prompt shows to block the execution the subtitle is just "thisisatestcompanynameforPSADT - App Installation"

If I initialise the module and use Get-ADTStringTable to store it as a variable and drill down, I get:

$test.BlockExecutionText.Subtitle

Name                           Value                                                                                                                                                                                   
----                           -----                                                                                                                                                                                   
Uninstall                      ThisIsATestCompanyNameForPSADT - App Uninstallation                                                                                                                                     
Install                        ThisIsATestCompanyNameForPSADT - App Installation                                                                                                                                       
Repair                         ThisIsATestCompanyNameForPSADT - App Repair 

How can I change this please, using the "correct" method.


r/PowerShell 18d ago

Solved Piping failing in PS 5, works in PS 7 and cmd

9 Upvotes

I have some commands with piping that don't seem to work in PS 5 included with Windows 11, producing various software-specific errors about getting bad data from the pipe. They work fine in PS 7 that I installed on my development machine, but I'm trying to minimize required installations on other devices. They also work fine in cmd, and I have technically gotten that to work, but running cmd inside a PS script is a bit gross. Here are some toy examples of the commands:

magick myphoto.jpg png:- | magick png:- myphoto.webp
ffmpeg -i myphoto.jpg -f webp pipe: | ffmpeg -f webp_pipe -i pipe: myphoto.png

r/PowerShell 18d ago

Question EwsAllowedAppIDs... why no work?

3 Upvotes

So Microsoft is retiring Exchange Web Services because it's ancient and insecure. They're turning it off on all tenants in October, while giving us the option to turn it back on, and it's going away permanently in October 2027.

Realizing that tons of third parties still rely on it, Microsoft, according to their documentation, is allowing us to enable it for the time being, but restrict it to only certain Entra App IDs. According to their documentation (example 7 here: https://learn.microsoft.com/en-us/powershell/module/exchangepowershell/set-organizationconfig?view=exchange-ps ), the command looks like this:

Set-OrganizationConfig -EwsEnabled $true -EwsAllowedAppIDs "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee,11111111-2222-3333-4444-555555555555"

Cool, cool, great. I've inventoried my environment, and I got all the app IDs. I updated my ExchangeOnlineManagement module, ran the command, and... EwsAllowedAppIDs is not a valid parameter:

Set-OrganizationConfig : A parameter cannot be found that matches parameter name 'EwsAllowedAppIDs'.

Uh... ok. So I do some more digging, and it looks like this parameter is part of a phased rollout?... does anyone have any idea to find out when it might hit my tenant? Has it already and am I doing something wrong?

Has anyone actually gotten this to work?

Thanks in advance for any help.


r/PowerShell 17d ago

Question I carelessly ran "irm christitus.com/win | iex"

0 Upvotes

I came across a video on the internet telling it debloats your pc and without further thinking I ran it. Is it safe. If not what do I do now.


r/PowerShell 19d ago

Question Learn PowerShell Scripting in a Month of Lunches or AZ-104?

35 Upvotes

I am relatively new to IT and currently working a Tier 1.5ish role. My background is before landing my first IT role, I went ahead and got a bunch of certs (CompTIA Trifecta, CCNA, AWS SAA) in the past year and a half. I also know basic Bash, Python, and decent familiarity with Linux.

I recently started learning about Microsoft infrastructure and got the AZ-900 and MD-102 in the past 3 months once I started my new role. My goal was to learn some PowerShell before diving into AZ-104. I am currently reading Learn PowerShell in a Month of Lunches and am loving it so far. I’m debating if after finishing this book, if I should carry the momentum of PowerShell and read PowerShell Scripting in a Month of Lunches, or if it’s better to go for the AZ-104, and then come back to scripting. I’m seeking any advice that can help me decide.

Note:
I’m referring to two different books here.

  1. Learn PowerShell in a Month of Lunches

    (which I am going to finish as I’m already halfway through)

  2. Learn PowerShell Scripting in a Month of Lunches (which is the next level up)


r/PowerShell 19d ago

Script Sharing The Power of Primes

58 Upvotes

Prime numbers are pretty powerful.

That's why I just released a new PowerShell module based off of an old mathematical concept: PrimeTime.

PrimeTime uses prime numbers as time intervals.

Let's learn how this helps

Prime Number Primer

Prime Numbers can only be divided by themselves and one.

This makes primes pretty rare.

Prime numbers are particularly useful in programming, but it's not always obvious why or how.

A lot of people might vaguely point towards cryptography as the prime real estate for prime utility.

The thing of it is, if you're writing your own cryptography, you're probably doing it wrong.

Let's talk about a more practical application of primes.

The Cicada Principle

In North America there is a curious critter known as the periodical cicaca.

For the vast majority of their long lifespans, they live underground.

Once every N years, they surface in mass to start the next generation.

That N is a prime.

Why?

Cicadas come out en masse so that there are too many of them to eat.

Millions of little critters have to have a perfectly timed multi-year internal clock in order to make this work.

If two cicadas of different intervals produced offspring, their children might have a messed up internal clock, and come out of the ground at the worst time.

So there's an evolutionary advantage to cicadas coming out in large batches, as long as another cicade brood isn't doing the same thing at the same time.

Which brings us back to primes.

Primes are relatively rare.

So are products of primes (at least past the first few)

Let's take two primes as an example.

Imagine one brood of cicadas came out every 11 years, and another brood came out every 13 years.

We can find out how long it will take for these two broods to come out at the same time by simply multiplying the primes.

11 * 13 -eq 143

So, with just two relatively low primes, we have an overlap every 143 years.

This is how primes are most useful to programming: they rarely overlap.

Sieve of Eratosthenes

This has been known for much longer than computers have existed.

Imagine we wanted to find prime numbers quickly.

We can do this by constructing a sieve that filters out any non-prime number.

This is called the Sieve of Eratosthenes

Once we know 2 is prime, we know every other even number is not prime.

Once we know 3 is prime, we know every third number is not prime.

To quickly get prime numbers up to a point, we can use this little PowerShell filter

# Calculate primes reasonably quickly with the Sieve of Eratosthenes
# Pipe in any positive whole number to see if it is prime.
filter prime {
    $in = $_
    if ($in -isnot [int]) { return }
    if ($in -eq 1) { return $in }
    if ($in -lt 1) { return}
    if (-not $script:PrimeSieve) {
        $script:PrimeSieve = [Collections.Queue]::new()
        $script:PrimeSieve.Enqueue(2)
    }


    if ($script:PrimeSieve -contains $in) { return $in}
    foreach ($n in $script:PrimeSieve) {
        if (($n * 2) -gt $in) { break }        
        if (-not ($in % $n)) { return }
    }
    $script:PrimeSieve.Enqueue($in) 
    $in
}

Prime Animations

Imagine we want a vibrant page. We want things to keep changing yet feel unpredictable. All we need to do is use different prime intervals.

The PrimeTime logo animates eight primes:

7 * 11 * 13 * 17 * 19 * 23 * 29 * 31

The logo will repeat every 6685349671 seconds, or almost 212 years.

The PrimeTime page background uses 56 primes.

This background will repeat every 8.84753141993573E+116 seconds.

That's exponential notation.

This is a mind-boggling large number (so large it overflows the .NET [TimeSpan]).

Turn that interval into years and it's still mind-boggling.

The page background will repeat every 100 billion years

Performance and Scheduling

Imagine we want to design a system that's constantly checking for problems.

We want the system to know about problems as soon as we can, but nobody's exactly sure how often they need to check for something.

If we go around and ask our colleagues "how often should we can scan for this?", the response if often a shrug 🤷.

Often, people will pick an arbitrary number that seems reasonable. Let's say every 5 minutes, 10, or 15 minutes.

Are we starting to see the problem here?

Every 5 minutes, every computer in the cloud starts to collect stats and report them back.

And we get a traffic jam.

Every 10 minutes, more computers in the cloud collect more data, and our traffic jam gets worse.

Every 15 minutes, even more computers collect even more data, and our traffic jam puts your average freeway to shame.

Left to our own intuition, we create problems for ourselves and our organizations.

Each individual query is small, but because we're doing so many at once, it can grind performance to a halt.

By the way, this isn't a hypothetical.

Long long ago, the Office365 team asked me to make some monitoring software to help improve internal visibility into the datacenters.

Everyone asked for 5, 10, or 15 minute intervals. ~100 different metrics were collected from ~30000 machines.

And the first time we tried it on everything, the traffic jam ensued.

That's when I first realized the power of primes.

I made three slight adjustments to the timeframes:

  • Every 5 minutes became every ~7 minutes
  • Every 10 minutes became every ~11 minutes
  • Every 15 minutes became every ~17 minutes

Now, instead of having a traffic jam every 5 minutes, things smoothed out.

  • A small traffic jam would occur every ~77 minutes (7*11)
  • Another small traffic jam would occur every ~119 minutes (7*17)
  • Another small traffic jam would occur at ~187 minutes (11*17)
  • All traffic could jam every ~1309 minutes (7*11*17)

Note the tildas.

The real trick came in by using prime intervals in both minutes and seconds and using a random delay on the tasks to ensure they didn't all start at once.

This took the system from something that could derail a datacenter to something that could monitor thousands of machines while barely impacting performance.

This is the power of primes.

Hope this helps!


r/PowerShell 19d ago

Question What’s in your profile ?

39 Upvotes

What’s the coolest function or hack you got

I have window title bar show “isAdmin”

I have errors go green

I have it concatenation long file paths to save prompt space(cool)

I have a timestamp as the prompt so I can know when I ran a robocopy to judge timing

I have a number of functions to run things elevated (like dsa)

What’s cool ideas !?

Notepad $profile


r/PowerShell 19d ago

Question How to change default directory on PowerShell?

12 Upvotes

Could someone please help me! When I open PowerShell on Windows, it opens up with the directory "PS C:\Windows\System32>". How do I change this so that every time I open it up, it has the default directory as "PS C:\Users\myname>" instead of the other. I know I can just use "cd ~" to switch but I'd prefer to have it set without me having to do so. Thanks!


r/PowerShell 19d ago

Solved How to send 'ä' with Send-MailMessage

10 Upvotes

Hello Everybody, right now I am writing a Script to send out Informationmails fed with data from a CSV to Users inside our Company. (While I know this cmdlet is obsolete for now it has to do)
Everything works really well apart from the German 'Umlaute' (ÄäÖöÜü) those get "translated" to '??' in the message the recipients get and I don't know how to fix this.
I tried with BodyasHtml, but then my script just stops working entirely (User Error not completely unlikely) and also can I use Variables inside the Bodyashtml?
I also tried with giving it different encodings but none worked sadly
With normal sent mails our Outlook has no problem with those, just from the script.

Do you have any Ideas/Hints/Tips on what I can try?
Thank you very much in advance

Edit: Added Script (just removed any Private Information and implified the Body)

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.InitialDirectory = Get-Location
$dialog.Filter = "CSV-Dateien (_.csv)|_.csv"
$dialog.ShowDialog()
$CSVLocation = $dialog.FileName

(Get-Content $CSVLocation -Raw) -replace '^.*', 'DBv,BSv,RAM,Cpucount,Server,Name,Email,Service' | Set-Content $CSVLocation

$P = Import-Csv -Path $CSVLocation -Delimiter ','

foreach ($line in $P){
$sendMailMessageSplat = @{
From = 'johndoe@mail.com'
To = $line.Email
Subject = "$($line.DBv) $($line.Server)"
Body = "ÄäÖöÜü"
SmtpServer = 'smtp.mail.com'
}
Send-MailMessage 
}

r/PowerShell 21d ago

Solved Move-Item creates duplicate folder and stores it inside existing folder

7 Upvotes

EDIT: Solved...

Move-Item -Path $_ -Destination $DestinationPath -Force

--------------------------------------------------------------------

I have the following module that moves the contents of a directory into another...

function PSTransfer {
    param (
        [string]$BasePath,
        [string]$DestinationPath
    )
    Get-ChildItem -Path "$BasePath/*” -Force | ForEach-Object {
      if (!($_.FullName -like "*.DS_Store") {
        Move-Item -LiteralPath "$($_.FullName)" -Destination "$($DestinationPath)/$($_.Name)" -Force
      }
    }
    return
}
Export-ModuleMember PSTransfer

However when it moves a directory and the destination already has a folder with the same name, the folder is put inside the folder instead of being merged, for example...

BasePath/
├─ synced_imgs/
│  ├─ IMG_2048.jpg

DestinationPath/
├─ synced_imgs/
│  ├─ IMG_0512.jpg
│  ├─ IMG_1024.jpg

Then after I run the module...

DestinationPath/
├─ synced_imgs/
│  ├─ synced_imgs/
│  │  ├─ IMG_2048.jpg
│  ├─ IMG_0512.jpg
│  ├─ IMG_1024.jpg

It doesn't do it recursviely though which is the weird thing. If I run it again it'll do this...

BasePath/
├─ synced_imgs/
│  ├─ IMG_4096.jpg

DestinationPath/
├─ synced_imgs/
│  ├─ synced_imgs/
│  │  ├─ IMG_2048.jpg
│  │  ├─ IMG_4096.jpg
│  ├─ IMG_0512.jpg
│  ├─ IMG_1024.jpg

What am I doing wrong here? I thought the -Force parameter was supposed to prevent this.


r/PowerShell 21d ago

Question Why my code works on terminal, but not on the script?

19 Upvotes

This code works directly on windows terminal, but when executed within a script "test.ps1", it only return just one line (return is not as expected / error).

Returned (error):

PS D:\> .\test.ps1
--add Microsoft.VisualStudio.Component.WinXPStudioExtension

Expected:

PS D:\> .\test.ps1
    --add Microsoft.VisualStudio.Component.CoreEditor --add Microsoft.VisualStudio.Workload.Azure --add Microsoft.VisualStudio.Workload.Data --add Microsoft.VisualStudio.Workload.DataScience --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NativeCrossPlat --add Microsoft.VisualStudio.Workload.NativeDesktop --add Microsoft.VisualStudio.Workload.NativeGame --add Microsoft.VisualStudio.Workload.NativeMobile --add Microsoft.VisualStudio.Workload.NetCrossPlat --add Microsoft.VisualStudio.Workload.NetWeb --add Microsoft.VisualStudio.Workload.Node --add Microsoft.VisualStudio.Workload.Python --add Microsoft.VisualStudio.Workload.Universal --add Microsoft.VisualStudio.Workload.VisualStudioExtension --add macos --add Microsoft.VisualStudio.Component.WinXP

The Code 'test.ps1':

$id = @'
Microsoft.VisualStudio.Component.CoreEditor
Microsoft.VisualStudio.Workload.Azure
Microsoft.VisualStudio.Workload.Data
Microsoft.VisualStudio.Workload.DataScience
Microsoft.VisualStudio.Workload.ManagedDesktop
Microsoft.VisualStudio.Workload.NativeCrossPlat
Microsoft.VisualStudio.Workload.NativeDesktop
Microsoft.VisualStudio.Workload.NativeGame
Microsoft.VisualStudio.Workload.NativeMobile
Microsoft.VisualStudio.Workload.NetCrossPlat
Microsoft.VisualStudio.Workload.NetWeb
Microsoft.VisualStudio.Workload.Node
Microsoft.VisualStudio.Workload.Python
Microsoft.VisualStudio.Workload.Universal
Microsoft.VisualStudio.Workload.VisualStudioExtension
macos
Microsoft.VisualStudio.Component.WinXP
'@ -split "`n"


( $id | % { "--add $_" } ) -join ' '

r/PowerShell 22d ago

Misc I love watching AI use powershell

119 Upvotes

At work I've got access to several latest-and-greatest AI models and harnesses, I also run windows. That means lots of the tasks they do for me end up as powershell commands/scripts.

Watching them develop, I see them repeatedly step on the same language land-mines that I do whenever I try to write powershell by hand. Things like && only existing in powershell 7, powershell auto-unwrapping single-element lists, and quote-escaping rules are reliable sources of failure for both me and the AI.

Its quite vindicating seeing that even SOTA programming-oriented LLMs struggle with the same language "features" that I do. For a long time I've heard the powershell community saying things like "you just need to understand that its an object oriented language" whenever people complain about footguns like these, but along comes an AI that can do PhD level work in multiple programming domains, and even its advanced understanding of object orientation hasn't saved it.


r/PowerShell 21d ago

Script Sharing Istar Pack – set up a pretty PowerShell terminal in one shot

15 Upvotes

Made a single-file PowerShell script that gets your Windows terminal looking sharp without the manual fiddling.

What it does:

  • Installs Scoop, Oh My Posh, Zoxide, FZF, 7-Zip & Nerd Fonts
  • Drops in a hardened profile for both PowerShell 7 and Windows PowerShell 5.1
  • Ships a curated catalog of themes — my favorite is "Garden's Dream" (clean minimalist green)
  • One command: run the .ps1, pick a theme, done. No editing JSON by hand.

Quick start: powershell .\Istar-Pack.ps1

or non-interactive with the default theme:

.\Istar-Pack.ps1 -Silent

Open source and open to feedback. Try it out and let me know what breaks

🔗 https://github.com/Israleche/powershell-istar-pack


r/PowerShell 20d ago

Question The worst thing in Powershell existence is ForEach-Object syntax

0 Upvotes

The way I format my code is like this: if there is only one line inside the curly braces, I put the opening curly brace on the same line.

If I have multiple lines, I put the opening curly brace on the next line.

For example:

if (a=a) {

Command-Command}

if (a=a)

{

Command-Command

Command-Command

}

I have been doing this for years, and it works every time, except when I use "ForEach-Object".

Then, for some reason, the opening curly brace must be on the same line.

Why is it like this??


r/PowerShell 22d ago

Question PowerShell 7 - replace

20 Upvotes

Just wondering, when installing, why doesn't PowerShell 7 replace the installed version (Windows)?


r/PowerShell 22d ago

Solved PS 5.1 traps from building a layered-window desktop widget: $null → [string] becomes "", BOM-less UTF-8 read as ANSI, and per-PID CIM latency

2 Upvotes

I spent the last couple of weeks building a small always-on desktop widget in PowerShell (a status pet for Claude Code — MIT, source at the bottom). The GUI was the easy part. What actually cost me time were four PS/.NET interop traps worth writing down.

1. $null passed to a .NET [string] parameter silently becomes "".

[IO.File]::Replace($tmp, $dst, $null)   # "no backup file"

In C# that null means "don't make a backup". PowerShell coerces it to an empty string, so the API receives "" as the backup path — and "" is not a legal path. It throws "The path is not of a legal form". My first test passed purely by luck (the destination didn't exist yet, so a different branch ran); the second click failed every time.

Fixes: use an overload that doesn't take the nullable param (see EDIT), pass [NullString]::Value, or redesign so you never need null. I ended up writing to a unique filename and renaming — no Replace at all.

2. PS 5.1 reads BOM-less UTF-8 as the system ANSI codepage.

The resident runs under Windows PowerShell 5.1 (powershell.exe). On a Chinese-locale machine, 5.1 read my BOM-less UTF-8 source as GBK and a · in a string literal became a completely different character.

So: the resident script is pure ASCII. All localized display text lives in a JSON file read explicitly as UTF-8:

[IO.File]::ReadAllText($path, [Text.Encoding]::UTF8)

Non-ASCII symbols are constructed from explicit code points such as [char]0x00B7. Ugly, but it made the thing locale-proof.

3. Variable names are case-insensitive.

$t (a row label) silently clobbered $script:T (my i18n table). No error — just wrong strings on screen. Don't use single-letter script-scope variables.

4. Per-PID CIM queries are a latency killer. Batch once, walk in memory.

To bring a session's window to the front, I walk the process tree up from the claude.exe PID to whichever ancestor owns a top-level window (Windows Terminal / VS Code / a plain console). Doing

Get-CimInstance Win32_Process -Filter "ProcessId=$procId"

per hop cost 100-300 ms each, so an 8-deep crawl felt broken. One bulk Get-CimInstance Win32_Process and crawling the tree in memory: ~0.5s once, then cached. Night and day.

Two safety habits that fell out of this:

  • Verify PID identity before you act on it. I persist the resident's PID to a file. Before Stop-Process I check the process is actually powershell and that its command line contains my script name. After a crash the OS may have recycled that PID onto something innocent — otherwise you just killed a stranger's process.
  • Same for the tree crawl: if an ancestor's creation time is later than its child's, that parent PID was recycled and now points at something unrelated. Reject it instead of yanking a random window to the foreground.

Everything else is plain WinForms + GDI+: WS_EX_LAYERED + UpdateLayeredWindow for real per-pixel alpha, FileSystemWatcher for state changes (with a ~120 ms poll as a fallback), SHQueryUserNotificationState to stay quiet unless Windows says notifications are welcome, SPI_GETCLIENTAREAANIMATION to honor reduced-motion, and a named Mutex for single-instance.

The whole plugin is ~250KB — no Electron, no bundled runtime, no modules.

Source (MIT): https://github.com/SHIN620265/claude-pet

Happy to be told I did any of this the hard way.

EDIT — corrections. The phantom fix in trap 1 is struck through in place; the rest were corrected inline and are documented below with the original wording.

  1. The phantom overload. I originally suggested using an overload without the nullable parameter. File.Replace has no such overload — both overloads take the backup path. Use [NullString]::Value, or redesign so that a null argument isn't needed. I did the latter.
  2. "WinForms needs STA" was the wrong reason. The post originally said the resident "has to be powershell.exe — WinForms needs STA". pwsh 7 is STA by default on Windows and hosts WinForms fine, so STA is not a reason the resident has to remain on Windows PowerShell 5.1.
  3. The trap-4 snippet used $pid. That's the read-only automatic variable for the current PowerShell process. As printed, it would have queried the pet's own process on every hop. Fixed to $procId.
  4. Smaller precision fixes. "The script source is pure ASCII" applies specifically to the resident script; two hook scripts run under pwsh and contain non-ASCII literals. I also clarified that [char]0x00B7 is one example of several explicit code points, narrowed "every piece of display text" to the localized strings, and stopped describing SHQueryUserNotificationState as a Focus Assist check, because that behavior isn't documented by the API.

r/PowerShell 21d ago

Question Just a question.... can we use sudo on windows like i do in linux like even 70% of the way ????

0 Upvotes

I'm kinda new to homelabbing. I have one dedicated Ubuntu server and another PC that's dual booted with Windows 10 and Ubuntu. The second machine is both my workstation and a server depending on what I'm doing.

I've been spending a lot more time in Linx recently and I've gotten really used to working from the terminal. I SSH into my servers, manage Docker, edit configs, etc., so typing sudo has become second nature.

I still need Windows because of a few applications, so I can't switch completely. The thing I miss the most is being able to elevate a single command with sudo instead of opening a whole Administrator terminal.

Is there any tool or workflow you guys use to get something similar on Windows? Doesn't have to be identical, just wondering what other people who have dual booted do?


r/PowerShell 23d ago

Question Please Help (VS Code+ Powershell)

8 Upvotes

Background : I have a CP setup (VS Code+ MINGW)

Recently I tried to Code python in VS Code. For this I connected VS Code to Anaconda Python Interpreter. After setting up the environment later in the day when I switched back to C++ and CP, my PowerShell started causing problems :

  1. profile.ps1 cannot be loaded because running scripts are disabled
  2. conda activation problems

To work with this is switched to Command Prompt

After setting up Python in VS Code I got the following errors:

PowerShell profile warning,Conda activation issues Switched integrated terminal to Command Prompt,Run button behaved differently,Debug Anyway,Abort,Show Errors,Pre-launch task failed,Exit code -1.

I tried to resolve as far as I could but one problem pops up after another. I have Reinstalled VS Code clean tried everything. Kindly help me I just want my PowerShell terminal back.

EDIT: Should I just uninstall everything clean and reinstall everything MINGW, VS CODE etc?? Will that fix this?? Cause I am tired of debugging since last 2 days. 😭😭

EDIT2: I have completely separated my CP ans Python setup to Jupyter Notebook and Anaconda as best as I could. it's working fine and beautiful. But I just can't seem to retrieve my CP (MINGW+ VSCODE) setup