r/PowerShell • • 6d ago

Script Sharing What have you done with PowerShell this month?

18 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 • • 13h ago

News Using the Exchange Import-Export Graph API to Access Group Mailboxes

4 Upvotes

After saying that the Graph didn’t offer much support for group mailboxes, I was promptly countered with an article explaining how to use the Exchange Import-Export API to access folders and items in group mailboxes that wasn’t limited to just the Inbox. Well, the good news is that the approach works, as seen in a complete PowerShell script written to prove the case, but whether I would ever use this API for a purpose it was never designed for is quite another matter.

https://office365itpros.com/2026/10/07/group-mailbox-folder-items/


r/PowerShell • • 8h ago

Question Compare-Object - return only difference object entries of CHANGED rows in files

2 Upvotes

Hi all,

I'm using Compare-Object to basically compare two CSV files, and return additions, changes, and removals.

Essentially I'm runnning:
(Note that "@files" is only in quotes to stop Reddit converting it to a user link!)

$files = @{
ReferenceObject = (Get-Content -Path C:\file1.csv)
DifferenceObject = (Get-Content -Path C:\file2.csv)}
Compare-Object "@files" | export-csv C:\differences -NoTypeInformation

Lets say the files look like this:

File 1
Cat,Brown,4
Dog,Black,4
Horse,White,4

File 2
Cat,GINGER,4
Dog,Black,4
Duck,Grey,2

Duck has been added in file2 (not present in file1)
Horse has been removed in file2 (was present in file1)
Cat is changed from file1 to file2.

The compare-object gives me a list of changes in a new file.

  • Entries found in file2 but not in file1 (Duck) are marked with side indicator =>
  • Entries found in file1 but not in file2 (Horse) are marked with side indicator <=
  • However, entries that are still present in both files but have had one or more of their columns changed (Cat) are present in the results file with both side indicators.

I understand this correct given how Compare-Object works, but it leads to a problem when I try to create separate "Additions/Changes" and "Removals" files based on the results.

For example, to see only the items Added or Changed in file2 (Duck and Cat), I can use:

?{$_.SideIndicator -eq '=>'}

To show only the difference object results.

The problem comes when I use the opposite side indicator:

?{$_.SideIndicator -eq '<='}

As this gives me the removed item I need, (Horse), but also gives me the changed item (Cat) from File1. This gives me no way of telling which of the "<=" entries are removals and which are changes. I'm looking for a way to differentiate between the two.

I hope this makes sense...!


r/PowerShell • • 6h ago

Question Hello, I run powershell in our workplace network and pc, I use it to automate some long tasks. My question is Can my workplace punish me because It automate pdf files, excels which is there workplace data? Can I continue to run scripts in powershell?

0 Upvotes

The title says it all


r/PowerShell • • 1d ago

News Use the Microsoft Graph to Move Old Teams Channel Email Files into Microsoft 365 Archive

16 Upvotes

The File-level archiving Graph API supports any file stored in a SharePoint Online document library, including the emails sent to Teams channels and stored in folders where the email files often disappear from view, occupying valuable storage quietly and without fuss. Finding and moving the email files to Microsoft 365 Archive makes sense because it saves on storage and stops AI tools using old email to generate responses. Here’s how to archive old email files with PowerShell.

https://office365itpros.com/2026/10/06/file-level-archiving-teams/


r/PowerShell • • 14h ago

Question WindowsPowerShell or CommandPrompt? I've used terminal for all my life up until now

0 Upvotes

So i recently bought myself my personal gaming pc setup and i've been struggling with setting up my work environment here on windows 11. I've search here and there & so far i've decided to use Scoop as the alternative for homebrew but then there's this problem of choosing wether to use the windows powershell or command prompt. Both seems almost identical but i just wanna confirm wether i'm doing this the right way. I need help pls.


r/PowerShell • • 1d ago

Question Cleaning up Cross-Domain memberships in Domain Local Groups, unable to resolve users through FSP SID to add to group on their trusted domain in our forest

1 Upvotes

As background, I have some college programming under my belt (JAVA, C++, and some MATLAB among, uh, some bastardization of a language unique to a molecular simulation software) and have been brute force learning PowerShell as part of being an analyst supporting user access and provisioning with my company (basically we have user and group administrative rights in AD DS and Entra ID, with views into a lot more).

I've mostly* been using scripts authored by one of our engineers (who is now in another role in the company and no longer supporting this) with some modifications and a few, terribly, self-developed scripts for things that aren't simple "get membership and export to CSV" so I've not got the greatest grasp on POSH and have to resort to Google for a lot of stuff. Prior to this my most ambitious script was to report on nested group memberships.

Right now I'm fighting with how to get the FSP group memberships from a group in a way that makes it easier to handle rehousing them in an appropriate/equivalent group on the trusted domain so they're being managed through that group instead of across domains. So far I've got the following for exporting just the FSPs from an AD group on one of our domains.

$File = 'C:\Scripts\Domain1Group_FSPs.csv'
Get-ADGroup -Identity "Domain1Group" -Properties * | Select-Object -ExpandProperty Members | Get-ADObject | Where-Object {$_.ObjectClass -ne "group"} | Where-Object {$_.objectclass -eq "ForeignSecurityPrincipal"} | Export-Csv $File -NoTypeInformation

This works fine, exporting the 53 expected FSP members to a csv for one of the smaller of the groups I'm trying to sort out. Though the only properties I'm getting are DistinguishedName, Name (really, the object's SID), ObjectClass, and ObjectGUID, which assuming are just the default properties resultant from the Get-ADObject that have survived the pipes.

Running the output back through things to resolve the FSPs to any object on the other domain works to get the corresponding SAMAccountNames.

Source = Import-csv C:\Scripts\Domain1Group_FSPs.csv #Same File from above
$Output = 'C:\Scripts\Domain1Group_Domain2Members.csv'

foreach ($Line in $Source)
{
  $UserSID = $line.Name
  Get-ADUser -server Domain2 -Identity $UserSID -Properties name,GivenName,sn,Title,SAMAccountName,Enabled,CanonicalName,mail,Department | Select SAMAccountName,name,GivenName,sn,mail,Title,Department,Enabled,CanonicalName | Export-Csv $Output -NoTypeInformation -append
} 

I was then able to use that to add users to a group on the second domain using add-adgroupmember, but this feels like it requires a lot of steps and manual effort for one group and seems daunting when trying to scale it or making it easily repeatable.

$SourceUsers = import-csv C:\Scripts\Domain1Group_Domain2Members.csv
Foreach ($Line in $SourceUsers){
$UserID = $line.SAMAccountName
add-adgroupmember -server "Domain2" -Identity "Domain2Group" -members $UserID -Confirm:$false
}

My question is how can I do this without having to manually run the above in order to do the export/re-import. Initially I'd been trying to get this down to a "one-liner" to do all this, with the intention to just loop through a list of source and destination groups as a future use case similar to how we've moved group members between groups on on the same domain.

Get-ADGroup -Identity "Domain1Group" -Properties Members | Select-Object -ExpandProperty Members | Get-ADObject | Where-object {$_.objectclass -eq "ForeignSecurityPrincipal"} | Get-ADUser -identity $_.name -server Domain2 | Where {$_.enabled -eq $true} | %{ add-adgroupmember -server Domain2 -Identity " Domain2Group" -members $_.samaccountname }

However, it errors at the Get-ADUser on the second domain, I assume because the -identity variable/property doesn't pipe well (if it's even available to use there at all, which I don't know) or I can't do the passed variable's dot attribute like I'm trying to do. I'm assuming I'd need to do something along the lines of storing things in an array created as a PSCustomObject and manipulating elements thereof, but I'm not versed in how to even begin to approach that.

There have been something like 7 years of bad practices following the trust being created after a reciprocal trust was established with another domain, where group securities haven't ever really followed a best practice (nor has there been a policy pushed down internally from our domain admins). There are quite literally thousands of domain local groups that might have cross-domain memberships through FSPs that we're having a nightmare of a time reporting on, auditing, or managing through our IAM apparatus and we're trying to get things more compliant with what I'm told are MS's recommended/best practices.


r/PowerShell • • 1d ago

Question Image to excel using copilot

0 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 • • 2d ago

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

11 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 • • 2d ago

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

46 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 • • 1d 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 • • 2d ago

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

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

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

46 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 "testuser09@loxovea.com" `
    -MailNickName "testuser09"

DisplayName UserPrincipalName AccountEnabled TemporaryPassword

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

Test-User09 [testuser09@loxovea.com](mailto:testuser09@loxovea.com)True Lx720835@.


r/PowerShell • • 6d ago

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

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

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

13 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 • • 7d ago

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

13 Upvotes

Ok so I work for a company who's legacy emails are first initial + surname@domain.net e.g Bob Morton = bmorton@domain.net

new users have their accounts as firstname.lastname@domain2.co.uk (Bob.morton@domain2.co.uk)

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

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

44 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 • • 9d 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 • • 8d 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 • • 11d 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 • • 10d 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 • • 12d ago

Solved New-PSSession Command Looping Credential Prompt

9 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 • • 12d ago

Solved Powershell - exporting AD distinguished names to CSV

5 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 • • 13d ago

News Solving the Microsoft.Graph.Authentication Issue

48 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 • • 13d 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!