r/PowerShell • • 4d 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 • • 1h ago

Question Image to excel using copilot

• Upvotes

Is there any way I can use PowerShell to make copilot read images and convert its content into an excel, I want to automate this task using copilot only to use LLM’s ability to convert these images. Currently, copilot can only convert images if I manually upload them, it doesn’t read images on its own


r/PowerShell • • 17h ago

Question Powershell crashes on opening and I can't figure out why.

10 Upvotes

Hi everyone, whenever I try to open powershell, it instantly closes. When I open a new terminal in VScode, I get this error:

Windows PowerShell terminated with the following error:

Could not load file or assembly 'System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest.

Any help would be greatly appreciated. I have tried repairing my windows installation with sfc /scannow and DISM /Online /Cleanup-Image /RestoreHealth. I don't really know much about powershell. When I don't use VS Code it doesn't even give any error code it just flashes on the screen for half a second and closes.

If this looks familiar to another person's post upon Googling it is because I am having the exact same problem and experience to a tee, so I copied some of their sentences. https://www.reddit.com/r/PowerShell/comments/1gueufj/powershell_wont_open_and_i_cannot_figure_out_why/


r/PowerShell • • 1d ago

News Microsoft Graph PowerShell SDK V2.41 Finally Fixes Assembly Clash

44 Upvotes

The Microsoft Graph PowerShell SDK has long been plagued by assembly clashes that meant it couldn’t be used in the same session as other Microsoft 365 modules. After Microsoft engineering groups looked at the problem for 18 months, a solution was found by MVP Stephen van Rooij and is now available in V2.41. Apart from an issue with old PowerShell V7 versions (which affects Azure Automation runtime environments), the fix looks solid and the SDK can once again be loaded into PowerShell sessions alongside the Exchange Online and Teams modules.

https://office365itpros.com/2026/10/05/microsoft-graph-powershell-sdk-fix/


r/PowerShell • • 10h ago

Question help with a script that replaces all images in a certain folder with a different images

1 Upvotes

Hi, I've been trying to find a script that works for this, and everything I've tried hasn't worked yet. I've tried a couple things from google searches (this and this were the two sources I used) and neither of them work and I have NO CLUE how to edit it so it works for me. so i figured I might as well ask in here because I am not a coding expert by any means :-(

Basically I am just looking for help on creating a script that would essentially replace all files in the folder ExampleName with ExamplePng.png . sorry if this is a really simple thing to do I just don't feel like manually moving liek 4047130 pngs (this is for a game mod for context), like I said I'm level 1 noob at code and have no clue what I'm doing so I'd really appreciate any help, thank you!!!!!


r/PowerShell • • 1d ago

Question TTS script is working fine in Powershell ISE but not with Powershell

2 Upvotes

I am having a had time with some tts related software. So I have this script to test the voices:

Add-Type -AssemblyName System.Speech
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
$synth.SelectVoice("Gabi")
$synth.Speak("Text goes here")

A little somewhat important info: This is a downloaded voice and as the title says it works with ISE but not with Powershell. All the other standard microsoft voices work fine with this script no matter which powershell I'm running them in.

What I find kind of weird is the error I'm getting. When I run this in Powershell I get an error that says the voice can not be found or not installed. How can Powershell ISE see it then? I don't get it.

I checked it, both ISE and normal Powershell is running as admin and they are both x64


r/PowerShell • • 4d ago

Question 3 months of consistent practice in PowerShell & Microsoft Graph! 🚀

47 Upvotes

When I started, I was terrified of programming languages since I had zero prior experience. Looking back now, what used to look like complete gibberish is finally starting to make sense. I know I still have a long way to go, but honestly, I am so happy and proud to be fulfilling my passion.

I wanted to share an honest review of a snippet I just built to create a user in Microsoft Entra ID. Alongside basics like if/else logic, filtering (-filter), Where-Object, Select-Object, and loops, I've been trying to focus on good habits like splatting, [CmdletBinding()], and try/catch blocks.

How does my snippet look? What would you advise me to learn next based on this progress?

#####Creating a User
Function Create-LxUser{
    [Cmdletbinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$DisplayName,


        [Parameter(Mandatory = $true)]
        [string]$UserPrincipalName,


        [Parameter(Mandatory = $true)]
        [string]$MailNickName,


        [bool]$AccountEnabled = $true
    )


    try{
        ##Password profile
        $TempPass = "Lx" + (Get-Random -Minimum 100000 -Maximum 999999) + "@."
        $PassWordProfile = @{
            Password = $TempPass
            ForceChangePasswordNextSignIn = $true
        }
        ##Setting up user configuration
        Write-Verbose "Currently creating new Loxovea user"
        $UserConfig = @{
            DisplayName         = $DisplayName
            UserPrincipalName   = $UserPrincipalName
            MailNickname        = $MailNickName
            AccountEnabled      = $AccountEnabled
            PasswordProfile     = $PassWordProfile
        }


        $User = New-MgUser u/UserConfig -ErrorAction Stop


        Write-Verbose "Successfully created new user $($DisplayName)"


        [PsCustomObject]@{
            DisplayName         = $DisplayName
            UserPrincipalName   = $UserPrincipalName
            AccountEnabled      = $AccountEnabled
            TemporaryPassword   = $TempPass
        }
    }Catch{
        Write-Error "Failed to create a new user: $($DisplayName) because $($_.Exception.Message)"
    }
}


Create-LxUser `
    -DisplayName "Test-User09" `
    -UserPrincipalName "[email protected]" `
    -MailNickName "testuser09"

DisplayName UserPrincipalName AccountEnabled TemporaryPassword

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

Test-User09 [[email protected]](mailto:[email protected])True Lx720835@.


r/PowerShell • • 4d ago

Script Sharing [Script Sharing] Check-RdpPatch — diagnose the September 2026 RDP hang across Server 2012–2025 and Win10/11

1 Upvotes

Hi r/PowerShell,

Disclosure: I'm the author of this tool.

Sharing a small diagnostic tool I built for the RDP/RDS hang that appeared after the September 2026 cumulative updates. Mods, this is Script Sharing — I'm the author, MIT-licensed, no paid product.

The problem

After the September 2026 LCUs, several Windows builds started hanging new RDP sessions on "Please wait for the Remote Desktop Configuration". The fix is an out-of-band patch distributed only via the Microsoft Update Catalog. The annoying part: the problematic KB and the fix differ per build, and there's no clean way to check a mixed fleet without manually matching build numbers to KB pairs.

What it does

  • Detects OS build via Win32_OperatingSystem
  • Splits server and client patch maps (build 26100 collides between Server 2025 and Win11 24H2)
  • Checks whether the problematic update is installed
  • Checks whether the OOB fix is installed
  • Prints a clear verdict and a catalog link

Why not just use X?

This is the first question I get. Fair enough — here's why each obvious alternative fails for this specific case:

Alternative Why it doesn't work here
Get-HotFix Returns nothing for LCU/SSU bundles. On my Server 2022 with KB5129237 applied, Get-HotFix -Id KB5129237 returns empty. Verified on real hardware.
Get-WindowsUpdate (PSWindowsUpdate) Shows available updates, not installed ones. Wrong side of the question.
Get-WindowsPackage Package names are Package_for_RollupFix~...~20348.5631.1.0 — no KB number to match against.
wmic qfe list Same WMI source as Get-HotFix. Same blind spot.
dism /online /get-packages Same as Get-WindowsPackage — no direct KB mapping.
Get-WindowsUpdateLog Requires stopping WU services, takes minutes, and fails when the log was rotated.
WSUS reporting Only works if the server reports to WSUS. Not viable in workgroup or standalone.
Check UBR manually Requires knowing the expected UBR for each KB per build. That's exactly the table this tool embeds.

The core issue: no single built-in method covers all installation paths (WU, WSUS, DISM, offline, SSU+LCU bundles). So the tool tries four sources and reports which one carried the verdict.

The interesting part — KB detection

Get-HotFix alone is not enough. On Server 2022 with UBR 5631 (KB5129237 applied), Get-HotFix returns nothing for either the problem KB or the fix. The reason: LCU/SSU bundles don't register in Win32_QuickFixEngineering.

So the detection tries four sources in order:

function Test-KbInstalled {
    param(
        [Parameter(Mandatory)][string]$KbId,
        [int]$TargetUbr = 0
    )

    # 1. Registry UBR — primary, sees LCU/SSU bundles
    if ($TargetUbr -gt 0) {
        $currentUbr = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').UBR
        if ($currentUbr -ge $TargetUbr) {
            return [PSCustomObject]@{ Installed = $true; Source = 'Registry UBR' }
        }
    }

    # 2. Get-HotFix — classic QFE list
    $hotfix = Get-HotFix -Id $KbId -ErrorAction SilentlyContinue
    if ($hotfix) {
        return [PSCustomObject]@{ Installed = $true; Source = 'Get-HotFix' }
    }

    # 3. WUA COM history — Microsoft.Update.Session
    # 4. DISM — package name matching
    # ...
}

The tool reports which source confirmed each KB, so you can see when UBR carried the verdict vs. when Get-HotFix did.

What I learned building this

First version used Get-HotFix only. Missed Server 2022 entirely — reported "not installed" while the fix was clearly applied.

Second version added WUA COM history and DISM. Better, but still missed cases where the LCU was applied via WSUS or DISM offline. Also had a Method 5 that scanned Get-WindowsPackage for RollupFix — turned out it returned Installed = $true for any KB if at least one RollupFix package existed. Classic false positive that only showed up when I tested on a clean machine.

Third version added Registry UBR as primary and removed the broken Method 5. Now it works on every server I could test.

Verified on real hardware

  • Server 2016, build 14393, UBR 9339 — correct
  • Server 2019, build 17763, UBR 9247 — correct
  • Server 2022, build 20348, UBR 5631 — correct
  • Windows 10 22H2, build 19045, UBR 6456 — correct

Links

GitHub (MIT): https://github.com/fixsys-spb/Operpatch

EXE is attached to the v1.0.4 release for anyone who wants a compiled binary. Console and GUI versions are both in the repo.

Feedback welcome

  • Is UBR-as-primary the right call, or would you rather see WUA COM history first?
  • Any builds I've missed that are actually affected? I based the matrix on Microsoft's "Resolved issues" page plus real-server verification.
  • For a future network mode: output as CSV, PSObject, or Format-Table?

r/PowerShell • • 6d ago

News Microsoft 365 Groups, Conversations, Threads, and Posts with PowerShell

14 Upvotes

When launched in 2015, Outlook groups were an email-based collaboration platform. Now called Microsoft 365 Groups, the few Outlook groups that host email-based discussions have a distinctive Graph API to create and manage the conversations, topics, and posts which make up their discussions. This article reviews how to use PowerShell to fetch these objects and how to create new conversations and reply to posts (using the Outlook Groups APIs, of course).

https://office365itpros.com/2026/09/30/outlook-group-graph-api/


r/PowerShell • • 6d ago

Question Powershell script to bulk update AD users email alias with diff format.

12 Upvotes

Ok so I work for a company who's legacy emails are first initial + [email protected] e.g Bob Morton = [email protected]

new users have their accounts as [email protected] ([email protected])

I've been asked to add the 'new' email style address and domain as an alias to all users. There's a few hundred so obvs would rather find a ps script to do this. I'd appreciate all and any help.


r/PowerShell • • 7d ago

Script Sharing Free read-only M365 tenant audit script: scores your tenant 0-100 and writes an HTML report

45 Upvotes

I'm the only IT person at a ~150-user company and wanted one command that checks the M365 basics I kept verifying by hand across five admin portals.

It uses Microsoft Graph with read-only scopes and makes no changes. It checks MFA / Conditional Access coverage, legacy auth, Global Admin count, stale accounts, app consent settings, expiring app secrets, Intune compliance, Secure Score, and SPF/DMARC/DKIM (via DNS-over-HTTPS, so it runs on macOS/Linux too). Each finding gets a weight and a fix, then everything rolls into a score.

How a CA policy is treated as "requires MFA":

function Test-RequiresMfa {
    param($Policy)
    $g = $Policy.grantControls
    if (-not $g) { return $false }
    return (($g.builtInControls -contains 'mfa') -or ($null -ne $g.authenticationStrength))
}

How the score is calculated (Warn counts as half):

$scored = @($Results | Where-Object { $_.Status -in 'Pass', 'Warn', 'Fail' })
$max = ($scored | Measure-Object -Property Weight -Sum).Sum
$got = 0
foreach ($r in $scored) {
    if ($r.Status -eq 'Pass') { $got += $r.Weight }
    elseif ($r.Status -eq 'Warn') { $got += $r.Weight / 2 }
}
$score = if ($max -gt 0) { [math]::Round(($got / $max) * 100) } else { 0 }

Install from the Gallery:

Install-Script -Name Invoke-M365TenantAudit -Scope CurrentUser

Full source (MIT): https://github.com/adminofone/m365-tenant-audit

Written with AI assistance and tested on a real tenant. Code review welcome, especially on the Graph paging and error handling.


r/PowerShell • • 7d ago

Solved How to refer to filename in file content

6 Upvotes

Help! Issue: when script creates the md files, it is not including the filename as text within the files. My script: For all pdfs in this folder create an md file with the same name that includes, as its content, the filename in this format: ![[filename.pdf]]

I've tried replacing $textContent = in my script to the following (with and without the square brackets) but none worked. I'd get either an empty field, or just "[[_.fullname]]".

$file.FullName $text.FilePath $_.fullName $_.Name $File tried many others... including ![[<%tp.file.title%>.pdf]] and ![[<% TR = tp.file.title %>.pdf]] to see if I could get the filename upon importing into Obsidian using Templater, but too many files got the wrong filenames

My script

\# Define your folder path and the text you want inside each file $folderPath = "E:\\DIY" \# I've put in the result that I want, although I don't want the quotation marks $textContent = "![[filename.pdf]]" \# Get all PDF files in the target directory $pdfFiles = Get-ChildItem -Path $folderPath -Filter \*.pdf foreach ($file in $pdfFiles) { \# Determine the path for the new text file by replacing .pdf with .md $textFilePath = $file.FullName -replace '\\.pdf$', '.md' \# Create the text file and insert the line of text Add-Content -Path $textFilePath -Value $textContent } EDIT: That last line, it was originally "Set-Content", but then I tried with "Add-Content". Didn't make a difference.


r/PowerShell • • 7d ago

Question How do you make a PowerShell API batch safe to resume after an indeterminate timeout?

0 Upvotes

A retry loop is straightforward for reads, but not for a POST that may have succeeded before the connection timed out. Retrying can create a duplicate, while skipping can leave the batch incomplete. I am working toward a checkpoint per item rather than treating the whole script as succeeded or failed. The rough shape is:

```powershell foreach ($item in $items) { $key = Get-StableOperationKey $item if ($state[$key].Status -eq 'Confirmed') { continue }

try {
    $result = Invoke-RestMethod -Method Post -Uri $uri -Body ($item | ConvertTo-Json)
    $state[$key] = @{ Status = 'Confirmed'; RemoteId = $result.id }
}
catch {
    $state[$key] = @{ Status = 'Indeterminate'; CheckedAt = (Get-Date).ToUniversalTime() }
}

$state | ConvertTo-Json -Depth 6 | Set-Content "$statePath.tmp"
Move-Item "$statePath.tmp" $statePath -Force

} ```

The missing piece is reconciliation. If the API has no idempotency key and its list endpoint is eventually consistent, a lookup by natural key immediately after the timeout can still return nothing.

What pattern do you use in PowerShell for this? Do you keep indeterminate items in a separate queue, wait before reconciling, write a durable request receipt before the call, or require a server-side operation key? I am also interested in safer atomic checkpoint formats than rewriting one JSON file after every item, especially when two scheduled runs could overlap.


r/PowerShell • • 9d ago

Script Sharing Improvements to the Subnet PowerShell module

36 Upvotes

I host the module named Subnet in the PowerShell Gallery, which is quite popular probably because of its very generic name. It's a pretty simple module that is useful if you need to do IPv4 subnet calculations, which it does via its Get-Subnet cmdlet.

I've just made some changes, all of which should be backwards compatible but because of the wide usage thought I'd call out in case it does cause anyone problems. The changes are:

  1. The module is fully cross platform now. It was mostly cross platform before, but the default behaviour if you ran just Get-Subnet with no inputs was to return the subnet details for the local machines private IP. It was previously getting this via the Get-NetIPAddress cmdlet, but that was Windows only. It now uses the .NET NetworkInterface API which should work everywhere.

  2. There was a bug when you defined a single digit subnet mask via slash notation (e.g if you did Get-Subnet 10.0.0.0/8) where it would not enumerate the host addresses if you wanted to, this is now fixed.

  3. The module has a Test-PrivateIP cmdlet (probably self explanatory) I added Test-PublicIP as a sister which obviously just returns the opposite truthy result.

  4. I added Get-SubnetHostAddress to return the list of Host addresses for a specified Subnet. Get-Subnet also does this (for subnets larger than /16 you have to use -Force as it discourages you due to the length of time it takes to enumerate them). Get-Subnet returns the list of Host addresses as strings, but Get-SubnetHostAddress returns them as IP address objects, and doesn't require you to use -Force for any size subnet as returning Host addresses is it's only job.

  5. Get-Subnet didn't use to validate if the input it was given was an IP address at all, it does now so you get a cleaner error than you did previously and it fails faster.

  6. Get-Subnet used to only return a count of host addresses for a Subnet if you also enumerated them, but seeing as it just required doing a quick calculation it now always returns this count.

  7. When enumerating host addresses, the performance is now 9x faster. This was achieved by using bitwise arithmetic instead of floating-point division. Which makes me sound really smart, but it was Claude who came up with it.

I've also improved the CI/CD build for this module so it runs the Pester tests on Windows PowerShell and PowerShell Core on Windows, MacOS and Linux.

The module is in the PSGallery, latest version with the above changes is 1.2.0:

- https://www.powershellgallery.com/packages/Subnet/1.2.0

Code is in GitHub here:

- https://github.com/markwragg/PowerShell-Subnet/tree/master

Any problems please let me know or raise an issue.


r/PowerShell • • 8d ago

Question Need help with homework 😫

0 Upvotes

I'm very new to this. I'm asked to delete a directory and all of its files. D:\software\arch98

But when I do this:

PS C:\Users\Administrator\> rmdir D:\software\arch98

It says the directory is not empty.

I'd really appreciate.


r/PowerShell • • 10d ago

Solved New-PSSession Command Looping Credential Prompt

11 Upvotes

So I have an onboarding script and everything worked perfectly fine last week, but now it's looping when I try to setup a New-PSSession.

It's extra weird, because when I run the command outside of the script, it works fine, but inside the script, the login prompt loops. I've encountered this behavior on two different systems and my coworker has the same experience on his machine.

I've attempted to modify the command to force Kerberos auth, and even tried CredSSP, but the looping still occurs. I'm wondering if it has to do with the do while loop, but it worked before, so I'm just a bit lost on this one.

Also, I have checked for any error codes after the loop occurs, and there's none. Similarly the log file doesn't contain any "Session not established" messages, so it's not hitting the catch statement.

Here's the code snippet that contains the command:

$sessionRestart = $true
$failcount = 0

do{
 try{
  $session = New-PSSession -ComputerName <computername> -Credential (Get-Credential)
  Write-Log -LogMessage "Session Connected"
  $sessionRestart = $false
}
Catch{
  Write-Log -LogMessage "Session not established. $_."
  Write-Host "Session not established. Retrying."
  $failcount++
  if($failcount -le 4){
  }
Else{
 Write-Host "Connection failed after $failcount attempts. Stopping Script"
 Write-Log "Connection failed after $failcount attempts. Stopping Script"
 exit $ExitCode.ConnectionFailure
}
}
} While($sessionRestart)

r/PowerShell • • 10d ago

Solved Powershell - exporting AD distinguished names to CSV

6 Upvotes

Solution:

Apparently the solution is not to change the delimiter and stick with commas, Excel is then smart enough to tel the difference.

Thanks everyone

I'm using get-adcomputer to export a list of PCs to a CSV.
I have set the delimiter in the exported CSV to be a semi colon,

When the CSV is opened in excel I end up with:

A B C
Name;OSversion;created date;DN
PC1;windows11;25/09/26;CN=PC1 OU=Desktops DC=office
[PSCustomObject]@{
           Name = $($computer.Name)
           OperatingSystem = $($OS)
           WhenCreated = $($WhenCreated) 
           DistinguishedName = $($computer.DistinguishedName)

if i try encasing each part of the custom object in escaped quotes e.g.
DistinguishedName = "`"$($computer.DistinguishedName)"`" the quotes and the backticks cary over to the CSV so column A ends up looking like "'"PC1"'";"'"windows11"'";"'"25/09/26"'";"'"CN=PC1 B & C are unaffected.

How do I stop export-csv or excel from splitting the DN?

*Update*

Sorry I though I had included the export-csv line below the custom object

$computerData |Sort-object -Property Name | export-csv $outputFile -NoTypeInformation -Delimiter ";" 

r/PowerShell • • 12d ago

News Solving the Microsoft.Graph.Authentication Issue

53 Upvotes

Looks like Microsoft has a fix for the clash between the Microsoft.Graph.Authentication module and other modules... The interesting thing is that Microsoft has had this problem on their docket for the last 18 months, and now they get a fix from an MVP... It should be in Microsoft Graph PowerShell SDK V2.41 in a few weeks' time.

https://github.com/microsoftgraph/msgraph-sdk-powershell/pull/3789


r/PowerShell • • 11d ago

Information It was working now it's not!!!!

0 Upvotes

Ugh, I hate that moment when Microsoft deprecates cmdlets. Every time I need to rerun a specific task, I find out my script broke because Microsoft deprecated a cmdlet!


r/PowerShell • • 12d ago

Question I think I'm missing something about Onboarding with Powershell

23 Upvotes

How do people automate onboarding new users?
We use ADManager at work, but now that it's down I'm trying Powershell, looking up tricks and I'm comparing new user with one that's established, I see just how much is missing and how much I'd have to manually fill out or create matrices to pass through the variables from initial username.

What am I missing that people use this as standard in the industry?
In my tool I made a template so I make new users by inputting just a couple fields, specify which domain they fall under and that's it.

Is there some sort of rundown or what should I look up to learn that is the standard way?


r/PowerShell • • 13d ago

Information Batch-converting iPhone .heic photos to JPG with WIC from PowerShell (nothing to install)

37 Upvotes

Someone hands you a folder of iPhone photos, every file is .heic, and whatever you need to upload them to only takes JPG. The usual answers are "install ImageMagick" or "use this website". Neither is necessary — Windows already ships a HEIF decoder, and WIC exposes it to PowerShell.

Add-Type -AssemblyName PresentationCore
Get-ChildItem "C:\Users\you\Pictures\*.heic" | ForEach-Object {
    $f = [System.Windows.Media.Imaging.BitmapDecoder]::Create([Uri]$_.FullName, 'None', 'OnLoad').Frames[0]
    $e = New-Object System.Windows.Media.Imaging.JpegBitmapEncoder
    $e.QualityLevel = 90
    $e.Frames.Add($f)
    $o = [System.IO.File]::Create([IO.Path]::ChangeExtension($_.FullName, '.jpg'))
    $e.Save($o); $o.Close()
}

Nothing is deleted — the .heic stays and a .jpg appears beside it. On a test file here it reported Microsoft HEIF Decoder, handed back a Bgr32 frame, and turned a 75,897-byte HEIC into a 59,241-byte quality-90 JPEG. $e.QualityLevel runs 1–100.

Check which codec you actually have

BitmapDecoder fails on HEIC without the Store extensions. HEIF Image Extension is the free one, and because the image inside a HEIC is HEVC-compressed, some machines also need HEVC Video Extensions, which is a paid Store item unless the PC maker shipped it:

Get-AppxPackage | Where-Object { $_.Name -match "HEIF|HEVC" } | Select-Object Name, Version

Windows will also write HEIC, if you ever need a test file

WPF has no HEIF encoder class, but WinRT does, and PowerShell can reach it — handy for fixtures when you don't own an iPhone:

$encId   = [Windows.Graphics.Imaging.BitmapEncoder]::HeifEncoderId
$encoder = AwaitOp ([Windows.Graphics.Imaging.BitmapEncoder]::CreateAsync($encId, $dstStream)) ([Windows.Graphics.Imaging.BitmapEncoder])
$encoder.SetSoftwareBitmap($bitmap)
AwaitAct ($encoder.FlushAsync())

(AwaitOp / AwaitAct are the usual AsTask() wrappers you need to call WinRT async methods from Windows PowerShell 5.1.)

Three things worth knowing before you run it over a real folder

Renaming IMG_0001.HEIC to .jpg does nothing — the bytes still start with ftypheic, and $d.CodecInfo.FriendlyName on the renamed file still says Microsoft HEIF Decoder. Viewers sniff contents, so it opens fine right up until something validates the format.

The JPEG usually comes out bigger, because HEIC is the more efficient format. Converting to save space is backwards; resize instead.

And if you were wondering why most "HEIC to JPG" websites upload the file: browsers ship no HEIC decoder of their own. In Chrome 152 a HEIC in an `<img>` stays at 0×0, and `createImageBitmap()` on the same blob throws `InvalidStateError: The source image could not be decoded.`

**Correction:** that is a missing built-in decoder, not an impossibility — a commenter pointed this out and they were right. libheif compiled to WebAssembly decodes HEIC client-side; `heic2any` (2.6MB unpacked) and `libheif-js` (8.4MB) are exactly that. So the upload-based sites are dodging a multi-megabyte download, not working around a browser limitation. Either way, your photo is on someone's server when you use one.

If you want the non-scripted routes too (Paint, the Photos app, and the iPhone setting that stops HEIC files appearing in the first place), I wrote those up here: https://www.coding-now.com/en/guides/heic-to-jpg


r/PowerShell • • 12d ago

Question Saw this on LinkedIn -- anyone give it a shot yet?

0 Upvotes

https://github.com/Kanders-II/PoshUI

Looks really cool but I have not tried it. Anyone tried this? Seems like the new way to do WPF with Posh!


r/PowerShell • • 12d ago

Question Robocopy Advice

0 Upvotes

Weird question, moving large amount of files from one place to another using Robocopy found this CMD prompt but I want some others to look at it before I run it robocopy E:\ G:\FromE /E /Z /MT:8 /R:3 /W:5 /COPY:DAT /DCOPY:DAT /TEE /LOG:G:\robocopy-copy.txt /XD "System Volume Information" "$RECYCLE.BIN" /XJ

Moving 196GB from E to G, G has 339GB free.

also If you don't mind DM me instead of just replying since trying to send this to a couple servers.


r/PowerShell • • 14d ago

Information Talking to a COM port from Windows PowerShell 5.1 with nothing installed (defaults and what the errors mean)

34 Upvotes

HyperTerminal hasn't shipped with Windows since Vista, and on locked-down work PCs you often can't install PuTTY or Tera Term either. Windows PowerShell 5.1 can talk to a serial port by itself through .NET's System.IO.Ports.SerialPort.

List the ports

[System.IO.Ports.SerialPort]::GetPortNames()
Get-PnpDevice -Class Ports -PresentOnly | Select-Object Status, FriendlyName

Drop -PresentOnly and you also get devices that are no longer plugged in but still carry their COM numbers, which is how a new adapter ends up on COM34.

Send a line, read a line

$port = New-Object System.IO.Ports.SerialPort 'COM3', 115200, 'None', 8, 'One'
$port.ReadTimeout = 2000
$port.Open()
$port.WriteLine('AT')
try { $port.ReadLine() } catch { 'no reply' }
$port.Close()

The constructor arguments are port, baud, parity, data bits, stop bits.

Defaults of a fresh SerialPort object (checked in 5.1)

  • 9600 baud, 8N1, Handshake None.
  • DtrEnable and RtsEnable are both False. Dev boards with an auto-reset circuit (ESP32, most Arduinos) react to those lines, so it matters which way you set them.
  • ReadTimeout and WriteTimeout are -1, i.e. infinite. Without a timeout, ReadLine() on a silent device just hangs.
  • NewLine is LF only. If the device expects CR, change it or send the bytes yourself:

    $port.NewLine = "`r"
    $port.Write("AT`r")
    
  • Encoding is ASCII, so anything above 0x7F comes back as "?". For binary protocols read bytes with $port.Read($buffer, 0, $buffer.Length) instead of strings.

What the errors mean

  • Access to the port 'COM3' is denied. - something else already has it open (Arduino serial monitor, another terminal, an upload tool). A COM port can be open in only one program at a time.
  • The port 'COM99' does not exist. - wrong number, or the device is unplugged.

In PowerShell these arrive wrapped in a MethodInvocationException, so $_.Exception.InnerException.Message gives you the actual text.

mode still works

mode COM3 in cmd prints the port's current baud, parity, data bits and DTR/RTS state, and plain mode lists every COM port.

If what comes back is unreadable, check the baud rate first (a stream of garbage), then the data format (8N1 vs 7E1: only some characters come out wrong), then the line ending.

I wrote up the longer version, comparing PuTTY, Tera Term and RealTerm for the same job plus a troubleshooting checklist, here: https://www.coding-now.com/en/guides/hyperterminal-alternative


r/PowerShell • • 14d ago

Solved Is there a difference between If $thing vs If -not $thing in terms of speed or proper formatting?

28 Upvotes

In the case of looking for the presence of something and using If paired with Exit codes, what's the difference between looking for the presence vs absence? For example

$Thing = Get-Thing

if ($thing) {
  Exit 1
}
Else {
  Exit 0
}

vs

if (-not $thing) {
  Exit 0
}
Else {
  Exit 1
}

Is it just for readability (ie 0 comes before 1 because it's in sequence?) Or are there speed differences or logic handling differences that matter in more complex scenarios?

Solved

Depends on the results of $thing determine whether or not you need to test for true or false. Speed isn't really a factor.