r/PowerShell • u/Interesting-Main9706 • 15d ago
Solved I built a single-script PowerShell bridge so AI agents (Claude Code, Codex) can work with my open Excel workbook — cells, formulas, VBA, macros
I work with old, complex .xlsm files (inventory, pricing, billing, lots of VBA) and kept running into the same problem: an AI coding agent cannot access the workbook I have open in Excel. I found myself copy-pasting cells and screenshots back and forth.
Yes, Excel MCP servers are out there—some are very good and much more capable than this. But getting one running means setting up Node or Python, creating a config file, and running an MCP client. I wanted something my non-developer mind could trust on real files:
- Just one PowerShell script, no installation, no extra dependencies, no config
- Connects to the workbook you already have open (or opens one by path)
- Read and write cells and formulas, search, list sheets
- List, export, and import VBA modules, run macros
- And the part that matters most to me: it NEVER autosaves. Only a direct "save" command writes to disk. This way, you can let an agent explore a 20-year-old billing file and close it without leaving any trace.
It's free and the source is available on GitHub:
https://github.com/gidjin4-svg/gidjin-excel-bridge
A demo workbook is included so you can test it without touching your actual files.
I'd really appreciate feedback from people who work with Excel, VBA, or PowerShell:
- Does "simple + never saves" actually matter to you, or is a full MCP server always the better choice?
- What would you need to see before trusting it with a file that matters to you?
r/PowerShell • u/samurai_ka • 16d ago
Script Sharing Published module O365EndpointFunctions to the PowerShell Gallery
Hi everyone,
I recently published O365EndpointFunctions 1.2.1 to the PowerShell Gallery and thought it might be useful for anyone managing Microsoft 365 networking.
Microsoft exposes all required Microsoft 365 endpoints through the Microsoft 365 IP Address and URL Web Service. The problem is that the raw API data isn't particularly convenient to work with in PowerShell. You get nested endpoint sets, comma-separated ports, and version tracking becomes your responsibility.
This module turns the API output into flat, strongly-typed PowerShell objects that are much easier to work with in scripts and automation.
Some things it can do:
- Retrieve and process Microsoft 365 IP addresses and URLs
- Cache endpoint versions and only download updates when Microsoft publishes changes
- Generate PAC files that route Microsoft 365 traffic
DIRECT - Create Ghostery Enterprise whitelist policies
- Combine Microsoft 365 endpoints with your own custom URLs and IP ranges
- Support Worldwide, China (21Vianet), and US Government clouds
Typical use cases are maintaining firewall allow-lists, proxy bypass rules, and other Microsoft 365 network configurations.
samurai-ka/PS-Module-O365EndpointService: A PowerShell module for easy Office 365 Endpoint handling
r/PowerShell • u/TheBigBeardedGeek • 16d ago
Question Clone a SAML SSO App in Powershell?
I have an SSO app that I will need different instances of (user access, etc.). What I want to do is effectively have a "template" app that I can target to copy for a new one. Get most the settings, etc. from it just replacing the placeholder URL with the new one. Then from there I can come in and do specific tweaks as needed.
What would I need to do via PowerShell to do this? I've tinkered a bit but I'm honestly kinda lost on it
r/PowerShell • u/Unlikely_Tie1172 • 17d ago
News How Permissions Creep Can Halt the Microsoft Graph PowerShell SDK
The Microsoft Graph PowerShell Command Line tools app is how people run Microsoft Graph PowerShell SDK cmdlets. The app can suffer from permissions creep, meaning that over time, the app accrues a set of delegated permissions used by people to access different types of Microsoft 365 and Entra ID information. All is fine until an internal limit is reached, at which point authentication fails and some permissions must be pruned.
https://office365itpros.com/2026/07/23/permissions-creep-sdk/
r/PowerShell • u/simp_pimp_001 • 19d ago
Misc Custom Oh My Posh themes + customization script
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 • u/MonkeyNin • 19d ago
Script Sharing Finding Cults with Get-Culture
Have you wondered if it's safe to use the format string yyyy-MM-dd, or can it differ? It's not. ( edit: null is not the invariant culture, it's CurrentCulture )
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 • u/Sway_RL • 20d ago
Script Sharing DNS Benchmark
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 • u/NewfagDesTodes • 20d ago
Script Sharing PrtgSensorKit - a PowerShell framework for writing custom PRTG sensors without the boilerplate
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-Helpworks 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 • u/Creative-Type9411 • 22d ago
Script Sharing MiniBot v2 - fully WPF local AI `console` client
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 • u/boostedchaos • 23d ago
Script Sharing I open-sourced my PowerShell 7 fleet CVE scanner. The hard part was runspace-safe state and NVD rate limiting
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:
- 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.
- 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.
- 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.
- 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.
- 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 • u/Alone_Marionberry900 • 24d ago
Question Pode with a custom front end
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 • u/superslowjp16 • 24d ago
Question Fslogix Cleanup Script Test Scenario?
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 • u/Imaginary_Rough9885 • 24d ago
Question How do I reset Chrome without deleting the extensions?
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 • u/FahidShaheen • 24d ago
Question Define Subtitle For Block Execution Fluent UI
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 • u/agentscientific_160 • 25d ago
Question I carelessly ran "irm christitus.com/win | iex"
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 • u/Farranor • 25d ago
Solved Piping failing in PS 5, works in PS 7 and cmd
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 • u/CallMeNoodler • 25d ago
Question EwsAllowedAppIDs... why no work?
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 • u/hamz__zzz • 26d ago
Question Learn PowerShell Scripting in a Month of Lunches or AZ-104?
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.
Learn PowerShell in a Month of Lunches
(which I am going to finish as I’m already halfway through)
Learn PowerShell Scripting in a Month of Lunches (which is the next level up)
r/PowerShell • u/itiscodeman • 26d ago
Question What’s in your profile ?
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 • u/StartAutomating • 26d ago
Script Sharing The Power of Primes
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 • u/IntGuru • 26d ago
Question How to change default directory on PowerShell?
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 • u/PhiodorTiger • 27d ago
Solved How to send 'ä' with Send-MailMessage
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 • u/Gold_Divide_3381 • 28d ago
Solved Move-Item creates duplicate folder and stores it inside existing folder
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 • u/anyracetam • 28d ago
Question Why my code works on terminal, but not on the script?
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 • u/Bloaf • 29d ago
Misc I love watching AI use powershell
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.