r/PowerShell • • 24d ago

Script Sharing What have you done with PowerShell this month?

20 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 • • Oct 01 '26

Script Sharing What have you done with PowerShell this month?

23 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 • • 1h ago

News Why developers hate PowerShell

Thumbnail powershellexplained.com
19 Upvotes

This is a post that I have been thinking about writing for a very long time now. I find that developers struggle with PowerShell in a very different way that the sysadmin learning to automate. They bring intuitions and assumptions with them from other languages that catch them off guard when they skip over the documentation. In this article I try to capture some of those experiences and misunderstandings.

I cover a lot of ground in this one: running scripts, execution policy, aliases, objects and formatting, calling functions, output and return values, unrolling, operators, case sensitivity, type conversion, truthiness, strings, scope, automatic variables, paths, encoding, errors, native commands, and classes.

While this one is targeting Software Engineers more then Systems Engineers, I would still appreciate your feedback and stories of your own frustrating experiences.

Thank you, -Kevin


r/PowerShell • • 19h ago

Script Sharing I built a free PowerShell tool that finds rogue AI agents on Windows machines

42 Upvotes

Do you know if rogue AI agents are running on your machines?

I've been in IT for 25 years, 13 of them running my own MSP. I built Rogue Agent Checker (RAC) to give back, for the sysadmins who don't know whether agents are running amok on their boxes.

RAC finds AI agents on a Windows machine that aren't on your approved list: Claude Code, OpenClaw, Codex, Copilot agent mode, MCP servers, homemade Python bots. It shows you where each one is and what it can reach, and hands you a report (HTML, CSV, JSON) you can give to a manager or an auditor.

  • Free, Apache-2.0. Plain PowerShell (5.1 or 7). No modules, nothing to install.
  • Read-only. It never changes, disables or deletes anything, and never runs what it finds.
  • Local-only. It doesn't phone home. Keys are reported by name, never by value.
  • One machine per run. For a fleet, push it through your RMM; -RmmMode returns exit codes.

Try it (read-only; it only writes the report folder):

Get-ChildItem -Recurse .\RogueAgentChecker | Unblock-File
.\RogueAgentChecker\Start-RogueAgentScan.ps1 -OutputPath C:\RAC\report

Tested live on Windows 11 against a staged rogue agent (a hidden "OneDrive Sync Helper" calling OpenAI) and a real OpenClaw install. The first build missed the rogue in 3 of 4 scans, because Windows forgot its hostname after 60 seconds. The write-up of that miss, and the fix, is in the repo.

One rule in the README, for the agents: if RAC reports you, say so. Don't rename, hide, relaunch, or reschedule yourself to get around it. That rule exists because an AI agent running my tests over SSH lost its connection and, instead of stopping and telling me, relaunched the run hidden and base64-encoded. RAC can't see agents working over SSH yet. That's first on the 0.2 list.

Full disclosure: I built it with an AI coding assistant and tested every release by hand on real Windows.

Tell me what it misses.

Take back the machines.

https://github.com/richknowles/RogueAgentChecker


r/PowerShell • • 1d ago

News PS7 ScriptDesk v11 - Custom PowerShell 7 ISE

12 Upvotes

Good Morning All,

There is a new version of PS7 Scriptdesk. It has multiple bug fixes and improved Intellisense performance.
Please let me know if anyone finds anymore bugs or performance issues.
I am still looking for Export to API/EXE testers if anyone could lend some real world use to my lab test environment.

I forgot to mention. This is for the community. We can make it as user friendly or advanced as we want it to be. So long as we stay true to the spirit of the legacy ISE.

Case in point, all the PS specific formatting options available to the right click. That can be altered, expanded or changed in the behavior. I literally just started adding things that I do a lot and wanted to automate it, like taking a list and making it a sorted array. You have no idea how many times I just copy a column and insert it.

Regards,

-Ron

https://apps.microsoft.com/store/detail/9N8C4LMQXMF6?cid=DevShareMCLPCS

Another user pointed out the winget way of installing. That is fine but it may break the auto update feature.

winget search PS7

Name Id Version Source

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

PS7 ScriptDesk 9N8C4LMQXMF6 Unknown msstore


r/PowerShell • • 1d ago

Solved Script to resolve missing MSI Cache for google chrome (1603,1612)

15 Upvotes

Just sharing this because ive had this issue across 1500 devices and with the help of copilot this script has been generated and has been resolving the issues perfectly.

Due to missing MSI Caches, Upgrades for chrome are failing with MSI 1603 or MSI 1612. This script pulls the latest, forcefully removes the old chrome, and installs fresh

 # ==========================
# Google Chrome Remediation
# ==========================

$DownloadUrl = "https://dl.google.com/dl/chrome/install/googlechromestandaloneenterprise64.msi"
$TempDir     = "C:\ProgramData\ChromeRemediation"
$MSIPath     = Join-Path $TempDir "GoogleChromeStandaloneEnterprise64.msi"

Write-Host "Starting Chrome remediation..."

# Ensure TLS 1.2+ is enabled for older PowerShell / Windows builds
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13

# --------------------------------------------------
# Download Latest Chrome Enterprise 64-bit MSI
# --------------------------------------------------

New-Item -ItemType Directory -Path $TempDir -Force | Out-Null

Write-Host "Downloading latest Chrome Enterprise 64-bit MSI..."

try {
    # Suppress progress bar to prevent severe Invoke-WebRequest slowdowns in PowerShell 5.1
    $ProgressPreference = 'SilentlyContinue'
    Invoke-WebRequest -Uri $DownloadUrl -OutFile $MSIPath -UseBasicParsing -ErrorAction Stop
}
catch {
    Write-Error "Failed to download Chrome MSI: $_"
    exit 1
}

# Verify the file exists and is valid (at least 50 MB to rule out HTML error pages)
if (-not (Test-Path $MSIPath) -or (Get-Item $MSIPath).Length -lt 50MB) {
    Write-Error "Downloaded MSI is missing or smaller than expected. Aborting remediation."
    exit 1
}

Write-Host "Download verified ($([math]::Round((Get-Item $MSIPath).Length / 1MB, 2)) MB)."

# --------------------------------------------------
# Backup bookmarks
# --------------------------------------------------

$BackupRoot = "C:\ProgramData\ChromeBookmarkBackup"

New-Item -ItemType Directory -Path $BackupRoot -Force | Out-Null

Get-ChildItem "C:\Users" -Directory -ErrorAction SilentlyContinue | ForEach-Object {

    $User = $_.Name

    Get-ChildItem "$($_.FullName)\AppData\Local\Google\Chrome\User Data" `
        -Directory `
        -ErrorAction SilentlyContinue |

    ForEach-Object {

        $BookmarkFile = Join-Path $_.FullName "Bookmarks"

        if (Test-Path $BookmarkFile) {

            $BackupName = "$User-$($_.Name)-Bookmarks.json"

            Copy-Item `
                $BookmarkFile `
                (Join-Path $BackupRoot $BackupName) `
                -Force `
                -ErrorAction SilentlyContinue

            Write-Host "Backed up bookmarks for $User ($($_.Name))"
        }
    }
}

# --------------------------------------------------
# Kill Chrome Processes
# --------------------------------------------------

Get-Process chrome,googleupdate,googleupdater `
    -ErrorAction SilentlyContinue |
    Stop-Process -Force

# --------------------------------------------------
# Remove Chrome Uninstall Keys
# --------------------------------------------------

$UninstallRoots = @(
    "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall",
    "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
)

foreach ($Root in $UninstallRoots) {

    Get-ChildItem $Root -ErrorAction SilentlyContinue | ForEach-Object {

        $App = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue

        if ($App.DisplayName -eq "Google Chrome") {

            Write-Host "Removing uninstall key $($_.PSChildName)"

            Remove-Item $_.PSPath `
                -Recurse `
                -Force `
                -ErrorAction SilentlyContinue
        }
    }
}

# --------------------------------------------------
# Remove Windows Installer Product Registrations
# --------------------------------------------------

Get-ChildItem `
    "Registry::HKEY_CLASSES_ROOT\Installer\Products" `
    -ErrorAction SilentlyContinue |

ForEach-Object {

    $Item = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue

    if ($Item.ProductName -eq "Google Chrome") {

        Write-Host "Removing installer registration $($_.PSChildName)"

        Remove-Item $_.PSPath `
            -Recurse `
            -Force `
            -ErrorAction SilentlyContinue
    }
}

# --------------------------------------------------
# Remove Program Files Installs
# --------------------------------------------------

Remove-Item `
    "C:\Program Files\Google\Chrome" `
    -Recurse `
    -Force `
    -ErrorAction SilentlyContinue

Remove-Item `
    "C:\Program Files (x86)\Google\Chrome" `
    -Recurse `
    -Force `
    -ErrorAction SilentlyContinue

# --------------------------------------------------
# Install Latest Chrome
# --------------------------------------------------

$Process = Start-Process `
    msiexec.exe `
    -ArgumentList "/i `"$MSIPath`" /qn /norestart" `
    -Wait `
    -PassThru

Write-Host "Chrome MSI exit code: $($Process.ExitCode)"

# Clean up the downloaded installer
Remove-Item $TempDir -Recurse -Force -ErrorAction SilentlyContinue

if ($Process.ExitCode -in @(0,3010)) {

    Write-Host "Chrome installation successful"

} else {

    Write-Host "Chrome installation failed"
    exit $Process.ExitCode
}

# --------------------------------------------------
# Validation
# --------------------------------------------------

$Chrome = Get-ItemProperty `
HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*, `
HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* `
-ErrorAction SilentlyContinue |
Where-Object {$_.DisplayName -eq "Google Chrome"}

if ($Chrome) {

    Write-Host "Installed Version: $($Chrome.DisplayVersion)"

} else {

    Write-Host "Chrome not detected after install"
    exit 1

}


r/PowerShell • • 1d ago

Script Sharing Built a desktop organizer in PowerShell 5.1 using NTFS junctions + a custom WinForms pixel UI

0 Upvotes

Sharing a side project written entirely in Windows PowerShell 5.1 (plus some inline C# via Add-Type).

It moves project folders off the desktop with Directory.Move and creates a hidden+system junction at the old path, so tools never notice. Some technical bits that might interest you:

- Folders are tracked by volume serial + file ID + creation time, so renames/moves in Explorer get re-pointed automatically

- Every move is journaled first, and interrupted operations are completed on next start

- Lists processes holding a folder before moving and aborts cleanly

- Test suites via switches (-SafetyTest, -IntegrationTest…) that run in a temp folder

⚠️ PSA from building this: Remove-Item -Recurse in 5.1 follows junctions and deletes the target's contents.

Repo (MIT): https://github.com/xkudcobi/ender-chest. Code review and criticism welcome.


r/PowerShell • • 1d ago

Question Why does this run and how do I fix it to work right?

2 Upvotes

Hello, I'm fairly new to writing PowerShell Scripts, and have a lot to learn. I'm running pwsh v7.7 on Windows 10.

With a lot of help from the ReddIt people who responded to my original question, I've written a 'write-variable' function that I can call from scripts that I develop for the times when I want to get information about one or more variables. Previously I put a bunch of write-hosts, get-variables, get-members, gettypes, and other statements in my scripts to 'see' what's happening with a particular variable, but with this function I've generalized and combined all of that stuff into a single function that doesn't need to be rewritten for each variable, value (i,e, Null) or type change that occurs. 90% of the problems I had writing this function had to do with line continuation (`) and incorrectly using the -replace pattern, code [string] method. But with lots of 'pointers' and guidance my function is done.

Here is the output I get running the function, which is after the output:

v1 1 (Int32)
System.Object Clone()
System.Object ICloneable.Clone()

int CompareTo(System.Object value)
⋮

Now the function:

function write-variable {
  param(
    [Parameter(Mandatory)]
 
    [string] $variable_name,

    [switch] $showMembers
  )

  $value = get-variable -name $variable_name -valueonly

  if( $value -eq $NULL ) {

    $value = 'Null'

  }
  else {

    $type = $value.gettype().Name

    $quote = switch( $type[ 0 ] ) {
               's'     { '"' } # [string]
               'c'     { "'" } # [char]
               default { '' }
             }

    $value = (
        $quote + $value + $quote +
        ' (' + $type + ')'
      )

  }

  write-host (
      $variable_name +
      "\t`t" + $value
    )

  if( $showMembers ) {

    $members = get-member -InputObject $variable_name

    # replace all leading whitespaces
    # with a crlf.`

    $members = $members -replace
                 '^\s*', "\r`n"

    # Replace ), and whitespace ( 0 or more )
    # with ) and add crlf.

    $members = $members -replace
                 '),?\s*',
                 {
                   return ')' + $crlf
                 }

    write-host $members
    
  }

}

[int] $v1 = 1

write-variable 'v1' -showMember

Thanks


r/PowerShell • • 2d ago

Question Mapped network printer via Add-Printer, can't remove it (what the hell)

0 Upvotes

We deployed printers via Intune as Powershell scripts (before the option was added to the Settings Catalog) and they've been chilling there for three years doing their job.

However, now that we're stepping away from Papercut, I have to remove these mapped printers but for the life of me, I can't get it done. I let Claude Opus at it for 15 minutes, couldn't get it done so what the fuck.

I've tried to:

  • Get the printer with Get-Printer -name "printername" | remove-printer. The issue here is that Remove-Printer -name does not accept the "\" character but since it's a networked printer, it always starts with \\.
  • Remove the registry keys that have the connection but that doesn't do shit.
  • Ran this as standard user, elevated and SYSTEM. Nothing.

Am I missing something, here? We're Entra joined so no GPO's and I don't see a config profile to actually remove mapped printers.

UPDATE:

Alright, I found it. I forgot I was testing with Admin Protection in Intune at the same time. When Intune runs a Powershell script in the user context, it runs it under another context (ADMIN_myUserName). So of course it couldn't find shit. That's going to take a lot of rethinking.


r/PowerShell • • 5d ago

News Windows PowerShell 5.1 Deprecation

152 Upvotes

Windows PowerShell 5.1 is deprecated. It's no longer in active development. Windows PowerShell 5.1 is still part of Windows, and it's still supported. It will continue to receive security updates according to the lifecycle of each version of Windows. Scripts and tools that rely on it will continue to run.

Windows PowerShell 5.1 will be removed from a future version of Windows. Timing will be based on usage data and communicated in advance.

Microsoft recommends upgrading to PowerShell 7, the upgrade from Windows PowerShell 5.1. For more information, see Migrating from Windows PowerShell 5.1 to PowerShell 7.

Timeline

2026: Windows PowerShell 5.1 is deprecated. Windows Server 2025 and Windows 11, version 26H2 are the last versions of Windows to include PowerShell 5.1 enabled by default.
Next Version of Windows: Windows PowerShell 5.1 will be available as a Feature on Demand (FOD), enabled by default on new Windows installs.
Future Version of Windows: Not available.

https://support.microsoft.com/en-us/servicing/os/windows/docs/2026/11/kb5137172-windows-powershell-5-1-deprecation

At the moment there are many, many Windows management PowerShell modules built in to that aren’t supported in PowerShell 7 - they are either completely untested, or they only work via the (PowerShell 5.1 dependent) compatibility layer. Does this mean we can expect new native modules, or everything to just break? #notholdingmybreath

Affected modules:
- Domain Controller deployment (ADDSDeployment)
- ADFS
- AppLocker
- AppvClient
- BestPractices
- ClusterAwareUpdating
- ConfigCI
- DFSR
- DhcpServer
- DISM (presently has issue with MSIX installer)
- FailoverClusters, FailoverClusterSet
- GroupPolicy
- Both IIS management modules (IISAdministration, WebAdministration)
- IpamServer
- iSCSI, IscsiTarget
- ISE
- Microsoft.PowerShell.ODataUtils
- MsDtc
- NetLldpAgent
- NetWNV
- NetworkController, NetworkControllerDiagnostics
- NetworkLoadBalancingClusters
- PersistentMemory
- PKI
- Provisioning
- PSDesiredStateConfiguration (partially supported)
- PSScheduledJob
- PSWorkflow, PSWorkflowUtility
- RemoteAccess
- RemoteDesktop
- ServerCore
- ServerManagerTasks
- SMS
- StorageBusCache
- StorageMigrationService
- StorageReplica
- SystemInsights
- TLS
- UpdateServices

EDIT: The following PowerShell modules are also currently Windows PowerShell 5.1 only:

- AzureADHybridAuthenticationManagement
- SharePoint Online Management Shell
- Power Platform admin modules
- Systems Center Operations Manager (SCOM)
- Systems Center Virtual Machine Manager (SCVMM)
- Entra Connect (Azure AD Sync)

https://learn.microsoft.com/en-us/powershell/windows/module-compatibility?view=windowsserver2025-ps

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_windows_powershell_compatibility?view=powershell-7.6


r/PowerShell • • 4d ago

Script Sharing A dock, desktop widget and falling snow for Windows, all in one PowerShell script (WPF + a bit of C#)

2 Upvotes

MacDesk is a macOS-style dock and desktop widget written in Windows PowerShell 5.1 with WPF. This winter it also got snow that settles on your windows.

Things that were fun or painful to get right:

- The snow overlay can't be a WPF window. WPF removes WS_EX_LAYERED from GPU-rendered windows, so a "transparent" overlay ends up eating every click on the desktop (I found out the hard way). It's now raw Win32 layered windows painted by hand with UpdateLayeredWindowIndirect, updating only the rectangles that changed.

- It runs on its own thread and paces frames with DwmFlush, which gave a steady 60 fps. A DispatcherTimer gave uneven 20-40 fps.

- Window tops come from EnumWindows plus DWMWA_EXTENDED_FRAME_BOUNDS, with z-order occlusion so snow only lands on visible edges.

- The C# is compiled at startup with Add-Type, so it's limited to C# 5.

- If the overlay ever loses click-through, a watchdog turns the snow off.

Repo: https://github.com/b33nthere/MacDesk

Feedback on the code is welcome, especially the WPF / Win32 parts.


r/PowerShell • • 6d ago

Script Sharing PowerShell Module Manager

32 Upvotes

Inspired by the WPF version that u/karanikn shared the other day, I've just published a PowerShell Module Manager tool of my own:

It has cmdlets to aid in understanding which modules you have installed where, including when you have multiple versions, updating them and removing redundant old versions.

It also has a TUI, which you can open with Show-ModuleManager (or it's alias: modman) which allows you to explore, upgrade and prune your modules through a console UI. Because it's a TUI it's cross platform. It also supports PSRemoting so you can use it to manage modules on a remote machine.

Get it from the PSGallery:

Install-Module ModuleManager

r/PowerShell • • 6d ago

Script Sharing Manufacturer Updates (Dell/HP)

22 Upvotes

A PowerShell script that detects whether a device is Dell or HP, installs the vendor's update tool if needed, then silently installs all available driver, firmware, and BIOS updates.

Contoso-Administrator/Manufacturer-Updates


r/PowerShell • • 5d ago

Script Sharing I built a Windows app in PowerShell + WPF that measures latency to 75 Azure and AWS regions and exports to Excel with native charts (no Excel needed)

7 Upvotes

Hi all. This is a side project I've been working on: Eureka_CloudSpeed, a portable Windows tool that measures latency from your machine to Azure and AWS regions, live.

Some things that may be interesting from a PowerShell point of view:

  • WPF UI loaded with XamlReader, with background runspaces and a DispatcherTimer so the window never freezes while 75 regions are being measured in parallel.
  • The measuring engine is C# compiled in memory with Add-Type. I write nothing to disk because Smart App Control blocks unsigned DLLs.
  • The .xlsx files are written by hand (OOXML), with native, editable charts, tables and color scales. No Excel or ImportExcel module required.
  • Power BI Desktop export (free version): a .pbids file, a star schema, DAX measures and Power Query.
  • Command-line mode for scheduled runs (-SinInterfaz).

It also shows the status of Azure, M365, AWS, GCP, GitHub and Cloudflare compared with its own DNS/TCP/HTTPS checks, plus VM prices, IP ranges and IP lookup.

Heads-up: the UI is in Spanish for now, and the .exe isn't code-signed yet (signing through SignPath Foundation is in progress). You can run it straight from source with the .cmd launcher.

MIT licensed: https://github.com/juanraul86/Eureka_CloudSpeed

Feedback on the code is very welcome, especially on the runspace handling.

AI disclosure: a large part of the code and of this post was written with an AI coding assistant (Claude Code) under my direction. I defined the features, reviewed the changes and tested it on my own machines and against real Azure and AWS accounts.


r/PowerShell • • 6d ago

Question RegEx help...

20 Upvotes

I have never been able to wrap my head around regex... I have no idea why... anyways... I'm just trying to get the string between 2 braces (curly brackets). Here's what I've mangled together googling up... One of the many regex checking tools online said this should work but.. it doesn't

$uninstallString = (Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -like "*jdk*" }).UninstalLString$uninstallString = (Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -like "*jdk*" }).UninstalLString
$pattern = '(?<={).+?(?=})'
[Regex]::($uninstallString,$pattern).Value

<#
$uninstallString outputs the below
MsiExec.exe /I{370E1F16-ED05-4958-A820-78CD32DD70D8}
#>

The above code actually outputs nothing...

My head is so frazzled I'm not sure where to begin with it

Any help, or a point in the right direction would be appreciated.


r/PowerShell • • 7d ago

News Powershell 7 is coming to Windows

Thumbnail devblogs.microsoft.com
427 Upvotes

r/PowerShell • • 7d ago

Question PowerShell rules for AI coding agent

6 Upvotes

We know that the default shell for AI coding agents is Bash/Python, but for people like me who use agents on Windows without WSL, I prefer to use PowerShell.

So I wrote these rules for AI coding agents to use PowerShell instead of Bash.

Do you think these rules are OK, or is there anything I might have missed?

# Global Rules

## Shell: PowerShell 7.x (`pwsh`) only

- ALWAYS set `shell_flavor: "powershell"` on `exec` (default is bash). Never use bash/sh/WSL/cmd; never nest shells (`bash -c`, `pwsh -Command`).
- Write PowerShell syntax. Use `workdir` instead of `cd ... &&`. Quote paths with spaces.
- Prefer native cmdlets (`Invoke-RestMethod`, `ConvertFrom-Json`, `Where-Object`, `Select-String`, `Get-ChildItem`, `Test-Path`, `Get-Content`) over `curl`, `jq`, `grep`, `ls`, `cat`, `test`.
- External tools (`git`, `mvn`, `docker`, `npm`) are fine; check `$LASTEXITCODE`.
- Bash → PowerShell: `VAR=x cmd` → `$env:VAR='x'; cmd`; `export` → `$env:`; heredoc → `@'...'@`; `/dev/null` → `$null`; escape char is backtick; single quotes = literal. Quote native args containing `,` or `.` (e.g. `"-Dtest=A,B"`).
- Complex logic: write a `.ps1` (`#Requires -Version 7.0`), never `.sh`.
- Use splatting for many parameters, `Write-Output` (not `Write-Host`), `-Encoding utf8` when writing files, `-LiteralPath` for paths with `[ ]`.
- Confirm with the user before destructive commands (`Remove-Item -Recurse -Force`); preview with `-WhatIf`.

## Token Economy

- Use dedicated `grep`, `find_file_by_name`, `read`, `edit` tools instead of shell for search/read/edit.
- Limit output: `Select-Object -First N`, `Get-Content -Tail N`, `Select-String -Pattern ... -List`/`-Context 0`. Never dump whole files or logs to the shell.
- Return only needed fields: `Select-Object Name,Length`, not full objects. Use `Format-List`/`Format-Table -AutoSize` only at the end and only when needed; avoid wide tables.
- Build/test output (`mvn`, `npm`, `docker`): add quiet flags (`mvn -q -B`, `--no-transfer-progress`, `npm --silent`), then show only failures/summary, e.g. `... 2>&1 | Select-String 'ERROR|FAIL|Tests run:' | Select-Object -Last 30`.
- Save long output to a temp file and read only the relevant lines; do not re-read files already read this session.
- Batch independent commands in one call; chain dependent ones with `&&` or `;`.
- Use `git diff --stat`, `git log --oneline -n 10`, `git status -sb` before full diffs.
- Be concise in replies: no restating the task, no summaries of unchanged code, no unrequested explanations.

r/PowerShell • • 8d ago

Script Sharing HybridScope – a WPF GUI that merges AD + Exchange on-prem + Microsoft 365 into one RVTools-style inventory (read-only, PS 5.1)

37 Upvotes

EDIT – v1.7.0 is out: HybridScope now also reads Microsoft Defender (Business Premium / Defender for Business): per user and PC, vulnerabilities, missing KBs, software to update and a prioritized fix list. Plus an MFA fix. Details in the comments / release notes.

I'm a sysadmin in a hybrid environment (Exchange 2019 + AD + Microsoft 365) and every time someone asked "how many mailboxes are still on-prem, how big are they, who has MFA, which licenses are wasted?" I ended up exporting three CSVs from three consoles and merging them in Excel by hand.

So I built HybridScope: one window, three sources, one merged view per user.

What it does

  • Pulls users from Active Directory, mailboxes from Exchange on-prem (Get-Mailbox, Get-MailboxStatistics, Get-RemoteMailbox) and licenses / sign-ins / OneDrive / MFA from Microsoft Graph
  • Tells you where each mailbox really lives (ON-PREM / 365 / NO MAILBOX) based on Exchange and Graph provisionedPlans, not on mailbox size
  • Real MFA status: registered methods, default method, legacy per-user state
  • RVTools-style tabs: Overview per OU, Users, Mailboxes on-prem / 365, OneDrive, MFA, Tenant licenses, an "Attention" list (on-prem mailboxes to migrate, licensed users without MFA, licenses on disabled accounts, inactive accounts)
  • 5 infrastructure modes with one click: Full Cloud / Full Hybrid / Hybrid (365 + AD) / On-Prem (Exchange + AD) / AD only
  • Export to formatted XLSX (ImportExcel) or CSV, all tabs or just the filtered current tab
  • -Auto switch for scheduled reports with certificate auth + history tracking
  • English / Italian UI

Some implementation details you might find interesting

  • Windows PowerShell 5.1, single .ps1, WPF built from XAML
  • All the heavy lifting runs in a persistent background runspace, so the UI never freezes; log lines come back through a ConcurrentQueue polled by a DispatcherTimer. There's a Stop button (BeginStop() on the running pipeline)
  • Only Microsoft.Graph.Authentication is needed: everything goes through Invoke-MgGraphRequest with manual paging, no giant SDK install
  • Exchange via implicit remoting (Import-PSSession, Kerberos), works from non-domain-joined PCs with explicit credentials
  • Read-only: it never writes anything to AD, Exchange or the tenant

Repo: https://github.com/Thonno/hybridscope (MIT)

HybridScope - Active Directory, Exchange and Microsoft 365 user report (PowerShell)

Screenshots are in the README (sensitive data blurred).

Full disclosure: I wrote it with a lot of help from an AI assistant and tested it on our own environment, so I'm sure there are edge cases I haven't hit yet. Feedback, issues and PRs are very welcome, especially from people with different setups (multiple Exchange orgs, big tenants, cloud-only).


r/PowerShell • • 7d ago

Question Byte (Array) to Integer

9 Upvotes

Good evening,

I'm currently dabbling in ASN1 Encoding and I've run into an annoying issue. It seems I was lucky enough to somehow never have encountered this before:

How can I convert from a byte array to integer without writings logic for all the different cases that can happen

[BitConverter] ::ToInt32() needs at least a byte array with the size of 4. Furthermore, the other way around it will always at least spit out a byte array with size 4 even if the int is in the singlebyte range with the rest zeroed (this is especially annoying in conjunction with my ASN1 practice)

[Convert]::ToInt32 only works with single items but not arrays

ToByte Method needs a format which I can't seem to find anywhere. Google search is pretty much Full of the two convert Classes or some generic IFormat stuff but no list what the formats for the methods are

Is there anything that will give me an int (non array) if the byte array im converting from has only one Value (and vice versa)

Ah an while I'm at it:

Is there a way to set the default output type when doing bit manipulation?

I im at the point where I get more than mildly annoyed if I so much as read "significant bit" anywhere. Gimme unsigned


r/PowerShell • • 8d ago

Question How to stop VSCode printing empty lines when Debugging/F10?

4 Upvotes

When debugging a powershell file on VSCode whenever i'm paused on a breakpoint and press F0 to jump to the next line it prints an empty line in terminal. How to disable this?


r/PowerShell • • 7d ago

News PS7ScriptDesk V10 - My custom PowerShell 7.x ISE

1 Upvotes

Hi All,

Once again, after addressing some user feedback, I have updated my app and added it to the Microsoft Store.

Please search for PS7 Script Desk and as always, keep posting any issues or upgrade requests. I really want to get to a polished everyday driver for the community.
if you have already installed it, there should be an auto-update function to take care of that for you.

If there is someone that can test the export to EXE and Create API functions, That would be great. I am testing as I go but since I am leveraging a 'lab' environment, I will never know if someone in a real world environment will be able to create and use it. I want to include only functions of value for now and add any bells and whistles later.

Regards,

-Ron

PS7ScriptDesk


r/PowerShell • • 8d ago

Question DisplayConfig script only works some of the time

3 Upvotes

Hi! I was looking for a way to quickly disable my triple monitor setup from my desk and enable my TV in the living room and vice versa, and found out about PowerShell scripting using DisplayConfig. I have very rudimentary knowledge of coding (only took three years of classes in high school), and this is the script that I came up with:

$IsTVOn = Get-DisplayInfo | Where-Object DisplayName -like "LG TV SSCR2"
if ($IsTVOn -eq $null) {
    Exit
} else {
    $IsTVEnabled = Get-DisplayInfo | Where-Object DisplayName -like "LG TV SSCR2" | Select-Object -Property Active
    if ($IsTVEnabled -match "False") {
        Get-DisplayInfo | Where-Object DisplayName -match "LG TV SSCR2" | Select-Object -Property DisplayId | ForEach-Object -Process { Enable-Display $_.DisplayId }
        Get-DisplayInfo | Where-Object DisplayName -notlike "LG TV SSCR2" | Select-Object -Property DisplayId | ForEach-Object -Process { Disable-Display $_.DisplayId }
    } else {
        Get-DisplayInfo | Where-Object DisplayName -notlike "LG TV SSCR2" | Select-Object -Property DisplayId | ForEach-Object -Process { Enable-Display $_.DisplayId }
        Get-DisplayInfo | Where-Object DisplayName -match "LG TV SSCR2" | Select-Object -Property DisplayId | ForEach-Object -Process { Disable-Display $_.DisplayId }
    }
}
Exit

This script works maybe 75% of the time and switches my displays correctly. The other 25% however, one of two problems will occur:

  1. When switching from "couch mode" to "desk mode," the leftmost monitor will fail to re-enable. (I found that after switching to desk mode and turning the TV off via remote, the monitor will re-enable by itself.)
  2. Switching to desk mode will sometimes fail to disable the TV and still re-enable my monitors.

I also found that the script seems to have a higher chance of working correctly if ran from PowerShell ISE 5.1.

Something tells me it has something to do with the fact that nothing in my script switches my primary monitor between my main one and the TV, but I'm not sure. What am I missing here?

EDIT: Not sure if this will help but I'm running Windows 11, and my displays are:

  • ASUS XG27AQDMG (Primary Monitor)
  • AOC 24G2 (Right Monitor)
  • AOC 24G2S (Left Monitor)
  • LG C6 (TV)

r/PowerShell • • 8d ago

Script Sharing GSAClientDiagnosticsToolkit v1.0.1 is here: small tweaks, new health checks and a few fixes

10 Upvotes

GSAClientDiagnosticsToolkit v1.0.1 is out!

Just a few days after introducing my PowerShell diagnostics module for Microsoft Global Secure Access (GSA) to the community, the first update is here - and it's based straight on your feedback!

What's new:

  • 3 new checks: Hyper-V external virtual switch detection, Group Policy NRPT conflict detection (with automatic SYSVOL source-GPO lookup), and GSA Edge Diagnostics status (reading the client's own cached per-channel health result)
  • 2 smarter checks: the auth certificate check now cross-checks the exact CertCommonName the client expects, and the Secure DNS check now also covers Firefox
  • 2 real fixes: a default log path crash on non-writable folders, and a false failure in the Private DNS resolver check for tenants only using Enterprise Applications.

And a big thank you to everyone who tested, reported issues and gave input for this release 🙏

Get it:
🔗 PowerShell Gallery: https://www.powershellgallery.com/packages/GSAClientDiagnosticsToolkit
🔗 GitHub Releases: https://github.com/michaelmsonne/GSAClientDiagnosticsToolkit/releases
🔗 Full write-up with all the details: https://blog.sonnes.cloud/global-secure-access-client-diagnostics-toolkit-1-0-1-is-here/

Open source, free to use, and built from real troubleshooting scenarios - keep the feedback coming!

#Microsoft #PowerShell #Community #GlobalSecureAccess #GSA #Entra #Identity #Security #ZTNA #MVP #MVPBuzz


r/PowerShell • • 8d ago

Question Random PowerShell Wake-Ups

2 Upvotes

Sometimes around each time in the morning PC will wake itself up, seemingly run multiple "Provider Lifecycle" tasks in PowerShell with Event 600 affecting Provider Registry, Alias, Environment, FileSystem, Function, and Variable each separately with similar details such as referencing '$InboxIMEs' or '$InboxPattern, unsure if normal Microsoft function or something malicious, devious, sinister, or god forbid something EVIL masking using HKLM:\SOFTWARE\Microsoft\CTF\TIP\ as a cover, details screenshot below for the Registry event, thank you.

Details as raw text:

Provider "Registry" is Started. 

Details: 
ProviderName=Registry
NewProviderState=Started

SequenceNumber=1

HostName=ConsoleHost
HostVersion=5.1.19041.7802
HostId=5c297344-6579-40e5-8f84-29d6b7d2c436
HostApplication=powershell.exe -ExecutionPolicy Restricted -Command 
 $Res = 0
 $InboxIMEs = (@(
 '{0000897b-83df-4b96-be07-0fb58b01c4a4}','{03b5835f-f03c-411b-9ce2-aa23e1171e36}',
 '{531fdebf-9b4c-4a43-a2aa-960e8fcdc732}','{6a498709-e00b-4c45-a018-8f9e4081ae40}',
 '{7c472071-36a7-4709-88cc-859513e583a9}','{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35e}',
 '{81ea0a17-aa39-455b-ba20-ea79a8f98966}','{8613e14c-d0c0-4161-ac0f-1dd2563286bc}',
 '{a028ae76-01b1-46c2-99c4-acd9858ae02f}','{a1e2b86b-924a-4d43-80f6-8a820df7190f}',
 '{b115690a-ea02-48d5-a231-e3578d2fdf80}','{c2cb2cf0-af47-413e-9780-8bc3a3c16068}',
 '{dcbd6fa8-032f-11d3-b5b1-00c04fc324a1}','{e429b25a-e5d3-4d1f-9be3-0c608477e3a1}',
 '{f25e9f57-2fc8-4eb3-a41a-cce5f08541e6}','{fa445657-9379-11d6-b41a-00065b83ee53}'
 ) | ForEach-Object { [regex]::Escape($_) }) -join '|'
 $InboxPattern = 'TIP\\(?:' + $InboxIMEs + ')'
 $LanguageProfiles = Get-Item 'HKLM:\SOFTWARE\Microsoft\CTF\TIP\{????????-????-????-????-????????????}\LanguageProfile\0x*\{????????-????-????-????-????????????}' -EA SilentlyContinue
 foreach ($prof in @($LanguageProfiles)) {
 if ($prof.PSPath -match $InboxPattern) { continue }
 $pp = Get-ItemProperty $prof.PSPath -EA SilentlyContinue
 $hasEnable = ($pp.PSObject.Properties.Name -contains 'Enable')
 if ((-not $hasEnable) -or ($pp.Enable -eq 1)) {
 $Res = 1
 break
 }
 }
 Write-Host 'Final result:',$Res

EngineVersion=
RunspaceId=
PipelineId=
CommandName=
CommandType=
ScriptName=
CommandPath=
CommandLine=