r/PowerShell 21d ago

Script Sharing What have you done with PowerShell this month?

48 Upvotes

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

Make sure to post a link to the code!


r/PowerShell 14h ago

Misc Custom Oh My Posh themes + customization script

16 Upvotes

Hey guys I created my own Oh My Posh themes for powershell (and wsl bash, cmd). I just wanted some aesthetically pleasing themes and the ones on the actual website were just not cutting it for me. So I created these. Moreover I created a simple script which can allow you to spin up your own theme in a matter of minutes. By your own theme I mean one where you control what segments go into the thing and also control the colors for it. Please do check it out and lmk how to improve and if there are any suggestions/feedback!

 

GitHub - oabdullah3/omi-posh: Oh My Posh themes for your terminal, designed by me


r/PowerShell 11h ago

Solved AdvantageBuilder: PowerShell GUI demo — super simple user input macro

0 Upvotes

I’ve put together a short demo showing how AdvantageBuilder can run interactive PowerShell scripts with simple GUI prompts.

(see comment for link)

The macro in the video is called Simple PowerShell GUI, and it demonstrates three built‑in commands:

  • prompt — ask the user for input
  • alert — display a message
  • confirm — yes/no dialog

Here’s the full macro source:

# get user input

$age = prompt "How old are you?" "20"

# get user confirmation

$question = "Are you really " + $age + "?"

$reply = confirm $question

if($reply)

{

alert("Your age has been confirmed!")

}

else

{

alert("Your age has NOT been confirmed!")

}

In the video, I show the macro inside the macro list, open it in the Macro Editor, run it from the editor, then close the editor and run it again by double‑clicking the macro in the list.


r/PowerShell 1d ago

Script Sharing Finding Cults with Get-Culture

6 Upvotes

Have you wondered if it's safe to use the format string yyyy-MM-dd, or can it differ? It's not. Unless you use InvariantCulture ( or null )

Save the expected string for comparison

#requires -PSEdition Core
$fStr     = 'yyyy-MM-dd'
$now      = Get-Date
$expected = $now.tostring( $fStr, ( [CultureInfo]::InvariantCulture) )

Next we can try formatting with every culture on your system. To do that, there is an optional culture argument for ToString like this:

DateTime.ToString( DateFormat, CultureInfo ) 

Next build a summary table with the formatted value and culture:

$cults    = Get-Culture -List
$summary = $cults | Foreach-Object {
    $dateString = $now.ToString( $fStr, $_ )
    [pscustomobject]@{
        Display = $dateString
        Name    = $_.DisplayName
        Culture = $_ # keep a reference to the object so you can drill down later
    }
}

Skip any cultures that are the same. Finally output using Join-String -f formatStr

$different = $summary | Group Display | ? Name -ne $expected
foreach( $item in $different ) {
    $title = "`nfor: $( $item.Name ) "
    $item.group
        | Join-String -f "`n - {0}" -Property Name -op $title
}

Here's what I get when $now is 2026-07-21:

for: 1405-04-30
 - Central Kurdish (Iran)
 - Persian
 - Persian (Afghanistan)
 - Persian (Iran)
 - Northern Luri
 - Northern Luri (Iran)
 - Mazanderani
 - Mazanderani (Iran)
 - Pashto
 - Pashto (Afghanistan)
 - Uzbek (Arabic)
 - Uzbek (Arabic, Afghanistan)

for: 1448-02-07
 - Arabic (Saudi Arabia)

for: 2569-07-21
 - Thai
 - Thai (Thailand)

r/PowerShell 1d ago

Question ProtonVPN split tunneling include mode issue with PowerShell 7

9 Upvotes

Adding the executable "C:\Program Files\PowerShell\7\pwsh.exe" doesn't work. What am I missing?

Note that PowerShell is the only app I'm having issues with. qBittorrent works totally fine. My goal is to have only Pwsh and qBit in the list of included apps.

When split tunneling is disabled, Pwsh uses the VPN connection just fine. With Include mode, Invoke-RestMethod doesn't work, and for the things that do work, my ISP IP is used instead of the VPN IP.

Invoke-RestMethod test:

> Invoke-RestMethod https://api.ipify.org
Invoke-RestMethod: The requested address is not valid in its context.

cURL test:

> curl.exe https://api.ipify.org
<My ISP IP>

I'm on Windows 10 21H2, ProtonVPN 5.1.5, Pwsh 7.6.3 x64.

I'm also using the Console Host, not Windows Terminal, if that matters.

Can someone explain how to properly set up PowerShell for this?

Thanks, everyone!


r/PowerShell 2d ago

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

45 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 2d ago

Script Sharing DNS Benchmark

14 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 4d ago

Question Powershell & Task Scheduler

28 Upvotes

I have tried probably a dozen different ways to get the Task Scheduler to send/pass a command to powershell to display a reminder message at a shutdown event. NOTHING HAS WORKED. I'm a newbie when it comes to powershell and windows task scheduler, but I do have programming experience in legacy software. I would appreciate any help and if you want to see my task scheduler set-up, I will be happy to share what I can. Thanks

UPDATE: Nothing I did using the Task Scheduler was able to work. However, I found a different approach, and it does work. I created (with searching assistance) an hta file that gave me the window I was trying popup, allowed me to customize the window, and performed the shutdown once I clicked the OK button. I pinned it the taskbar right after the search box and now I just click that to begin the process.


r/PowerShell 3d ago

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

5 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 5d 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 5d 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 4d ago

Script Sharing Thank you, PowerShell. I didn't know that.

0 Upvotes

PS C:\> Is-Mobile No

(To do this, I added a function to my profile. To access your PowerShell profile, run notepad $profile (If it doesn't exist, run New-Item -Type File -Path $PROFILE -Force))

The function I added:

function Is-Mobile {
    Write-Host "No"
}

r/PowerShell 6d 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 6d 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 6d ago

Question Define Subtitle For Block Execution Fluent UI

3 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 7d ago

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

8 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 7d ago

Question EwsAllowedAppIDs... why no work?

4 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 6d 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 7d ago

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

37 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 8d ago

Script Sharing The Power of Primes

57 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 8d ago

Question What’s in your profile ?

40 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 8d ago

Question How to change default directory on PowerShell?

13 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 8d 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 = '[email protected]'
To = $line.Email
Subject = "$($line.DBv) $($line.Server)"
Body = "ÄäÖöÜü"
SmtpServer = 'smtp.mail.com'
}
Send-MailMessage 
}

r/PowerShell 9d ago

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

8 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 10d ago

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

18 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 ' '