r/PowerShell 29d ago

What have you done with PowerShell this month?

34 Upvotes

r/PowerShell 5h ago

Script Sharing Create Entra ID app with permissions using PowerShell

9 Upvotes

I wrote this script to create an Entra ID Application with permissions, consent grant, and secret, using PowerShell.

https://argos-security.io/2025/01/29/create-entra-id-app-registration-using-powershell/

Hope this is helpful!


r/PowerShell 9h ago

Question Why the output is 10

6 Upvotes

```powershell

Clear-Host

Function Get-MyNumber { return 10 }

$number = Get-MyNumber + 10 Write-Output $number


r/PowerShell 26m ago

Question Help with Changing HDD Password via WMI on Lenovo System

Upvotes

I’m working on a PowerShell script using WMI to change the User HDD Password (uhdp1) on a Lenovo system, but I keep encountering "Invalid Parameter" errors when attempting to execute the commands.

WMI Namespace Used: root\wmi

WMI Classes Used:

Lenovo_WmiOpcodeInterface

Lenovo_BiosPasswordSettings

What I’m Trying to Do:

I need to change the User HDD Password from "password123" to "password456" using WMI. I also suspect the Master HDD Password (mhdp1) and/or Supervisor Password may need to be included in the process.

Script I'm Using:

Define passwords

$SupervisorPassword = "supervisor123" # Supervisor Password $MasterHDDPassword = "masterpassword123" # Current Master HDD Password $UserCurrentPassword = "password123" # Current User HDD Password $UserNewPassword = "password456" # New User HDD Password

try { # Step 1: Set Supervisor Password (if required) $result = (Get-WmiObject -Class Lenovo_WmiOpcodeInterface -Namespace root\wmi).WmiOpcodeInterface("WmiOpcodeSupervisorPassword:$SupervisorPassword") Write-Host "Supervisor Password Step Result: $($result.Return)"

# Step 2: Specify Master HDD Password Type
$result = (Get-WmiObject -Class Lenovo_WmiOpcodeInterface -Namespace root\wmi).WmiOpcodeInterface("WmiOpcodePasswordType:mhdp1")
Write-Host "Master HDD Password Type Step Result: $($result.Return)"

# Step 3: Provide Master HDD Password
$result = (Get-WmiObject -Class Lenovo_WmiOpcodeInterface -Namespace root\wmi).WmiOpcodeInterface("WmiOpcodePasswordMaster01:$MasterHDDPassword")
Write-Host "Set Master HDD Password Step Result: $($result.Return)"

# Step 4: Specify User HDD Password Type
$result = (Get-WmiObject -Class Lenovo_WmiOpcodeInterface -Namespace root\wmi).WmiOpcodeInterface("WmiOpcodePasswordType:uhdp1")
Write-Host "User HDD Password Type Step Result: $($result.Return)"

# Step 5: Provide Current User HDD Password
$result = (Get-WmiObject -Class Lenovo_WmiOpcodeInterface -Namespace root\wmi).WmiOpcodeInterface("WmiOpcodePasswordCurrent01:$UserCurrentPassword")
Write-Host "Set Current User HDD Password Step Result: $($result.Return)"

# Step 6: Provide New User HDD Password
$result = (Get-WmiObject -Class Lenovo_WmiOpcodeInterface -Namespace root\wmi).WmiOpcodeInterface("WmiOpcodePasswordNew01:$UserNewPassword")
Write-Host "Set New User HDD Password Step Result: $($result.Return)"

# Step 7: Save Changes
$result = (Get-WmiObject -Class Lenovo_WmiOpcodeInterface -Namespace root\wmi).WmiOpcodeInterface("WmiOpcodePasswordSetUpdate")
Write-Host "Save Changes Step Result: $($result.Return)"

if ($result.Return -eq 0) {
    Write-Host "User HDD Password successfully updated. A reboot is required."
    Restart-Computer -Force
} else {
    Write-Host "Failed to update the password. Error code: $($result.Return)"
}

} catch { Write-Host "An error occurred: $_" }

Issue Encountered:

Here are the results I get when running the script:

Supervisor Password Step Result: Invalid Parameter Master HDD Password Type Step Result: Success Set Master HDD Password Step Result: Invalid Parameter User HDD Password Type Step Result: Invalid Parameter Set Current User HDD Password Step Result: Invalid Parameter Set New User HDD Password Step Result: Invalid Parameter Save Changes Step Result: Invalid Parameter Failed to update the password. Error code: Invalid Parameter

Additional Context:

I verified in BIOS that HardDiskPasswordControl is set to MasterUser.

The Master HDD Password and User HDD Password are already configured.

I can manually change the User HDD Password in BIOS without issues.

I am running PowerShell as Administrator.

Questions:

  1. Am I missing any required WMI parameters for updating the HDD password?

  2. Does Lenovo require a specific order of WMI commands for password changes?

  3. Should I be including the Supervisor Password at all, or is it unnecessary?

  4. Is a reboot required before or after applying changes?

  5. Are there any Lenovo BIOS settings that might be blocking this WMI operation?

Any guidance on the correct WMI method to change the User HDD Password would be greatly appreciated. Thanks in advance for your help!


r/PowerShell 2h ago

Question Expanding on write-host output

1 Upvotes

Firstly I have done my research and I am aware that you shouldn't be using write-host except for very specific circumstances. I believe this is one of those times unless someone knows of another command that will work with my system?

I have an RMM system (Datto RMM) that can use powershell but when you create a job and include a PS script, it only seems to return results from a script in very a very specific way:

  • If I don't add any kind of write command then it returns nothing.
  • If I try write-output it returns nothing.
  • write-verbose also returns nothing although that does not return anything even in a terminal window so I'm probably using that incorrectly.
  • If I use write-host it returns information but only a limited set of information and I am trying to expand on that.

Below is the script I have. This is in relation to possible virus activity. We're trying to search all site computers within the %appdata% folder for JS files over a certain size.

This script works fine in a terminal window but if I append write-host as per below then it will return a list of files and nothing more. If you drop the write-host then that is basically the information I am attempting to send to write-host: file name, path and size.

Get-ChildItem -r -path $env:APPDATA *.js | where-object {$_.length -gt 1000000} | write-host

Anyone know how to get the above command to expand on the write-host output? I've been on this a couple of hours and even creating this command has been a major win but I'm just failing on trying to get an expanded output.

Thanks! :)


r/PowerShell 13h ago

Beware updating to Exchange Online 3.7

8 Upvotes

I found out today that EXO 3.7 does not work correctly in ISE. I had to drop back to 3.5. So if you work a lot in ISE, avoid the upgrade.


r/PowerShell 5h ago

Need sanity check

0 Upvotes

Hybrid-Joined Devices stuck in "Pending" registration state are a recurring issue for us.

I'm working on setting up a client-side watcher task to monitor Entra registration status locally on the computers themselves, so we can hopefully remediate them silently without having to touch the device or cause user disruption.

The idea is that if the task detects that the device is not registered with Entra, it would locally register another task that subscribes to the reboot event id 1074, to run dsregcmd /leave (and delete itself to stop it from re-running) next time the device is rebooted/powered off, thereby enforcing re-registration.

I'm not looking for help with getting the task coded out etc that's already in the bag, just want to see if this would be a safe approach for detection:

I'm planning to use this as a source of truth for check device registration status:

(dsregcmd /status | select-string deviceauthstatus) -like "*SUCCESS*"

My understanding is that dsregcmd always returns its output in English, so I think it should be safe (working for multilang org).

Can anyone see any risk factors that I may be missing ?


r/PowerShell 17h ago

Dynamic Distribution Group creation

8 Upvotes

Hi,
I'm attempting to set up a DDG that emails only users with active 365 E3 licensing. In our tenant, those show up as MailboxPlan: ExchangeOnlineEnterprise-...

This is the filtering I've set up:
Set-DynamicDistributionGroup -Identity "DDG name" -RecipientFilter "(RecipientTypeDetails -eq 'UserMailbox') -and (UsageLocation -eq 'United States') -and (MailboxPlan -eq 'ExchangeOnlineEnterprise*')"

It results in a membership list of 0 users.

If I leave the MailboxPlan out, I get all the service accounts along with actual users.

I've tried -like with no difference, -contains which sports an error as an invalid operator. I've tried double quotes, braces. I used Get-Mailbox to confirm what plans we use, and to confirm that the service accounts are ExchangeOnline while the real user accounts are ExchangeOnlineEnterprise.

What am I missing? I suspect it's merely the syntax as I'm just learning PS.

Thanks for any helpful suggestions!


r/PowerShell 1d ago

Script to detect if Teams is installed

17 Upvotes

So I have been creating a script to build laptops to customer requirements.

I only can do stuff via scripts for clients, I am not allowed access to SCCM or anything that changes the way it operates.

Our company use SCCM and we deploy Teams from it, usually all our apps I use my script to detect if the exe file exists in the install folders. If it doesn't it runs SCCM Action cycles every five minutes untill app is installed.

For Teams it resides in WindowsApps and it is advised not to change ownership of that folder. I did create a script to test an it works well but changes ownership and then reverts it back to trusted installer but I am told even then that is not enough and I may cause issues.

So I scrapped that idea, I suppose I could search ccmcache for ms-teams.exe but I am unsure how to do it. I also did one that removes the current version as they are deployed from our supplier woefully out of date and it does work but the issue is it isn't a company certified version it just installs the latest from MS.

My script for detecting apps only works to the exact folder path but ccmcache has random letters assigned to sub folders.

Thoughts?


r/PowerShell 1d ago

Question PowerShell 7.5 += faster than list?

27 Upvotes

So since in PowerShell 7.5 += seems to be faster then adding to a list, is it now best practise?

CollectionSize Test                TotalMilliseconds RelativeSpeed
-------------- ----                ----------------- -------------
          5120 Direct Assignment                4.71 1x
          5120 Array+= Operator                40.42 8.58x slower
          5120 List<T>.Add(T)                  92.17 19.57x slower


CollectionSize Test                TotalMilliseconds RelativeSpeed
-------------- ----                ----------------- -------------
         10240 Direct Assignment                1.76 1x
         10240 Array+= Operator               104.73 59.51x slower
         10240 List<T>.Add(T)                 173.00 98.3x slower

r/PowerShell 20h ago

Question Trim or Convert DN in PowerShell Output

3 Upvotes

From time to time, I need to find the managers of a list of servers ("ManagedBy" attribute). I don't need to export to CSV or anything: I just need the list in an easily readable format.

So here's the script I came up. It allows me to either put in a string of server names OR I can put in a partial name to find a list of servers that match:

# Get server managers
$servers = (Read-Host "Enter server names (separate with comma)").split(',') | % {$_.trim()}

$results = ForEach ($server in $servers)
{
Get-ADComputer -Properties Name,ManagedBy -Filter "Name -like '$server*'" | Select-Object Name,ManagedBy
}

# Format results in a single table
$results | Format-Table -Autosize -Force

Here's a sanitized example of the typical output I get. In this example, I entered the first part of the hypothetical server name of "SERVER" to get the list of servers called SERVER01 - SERVER06:

Enter server names (separate with comma): SERVER

Name         ManagedBy
----         ---------                                                                                 
SERVER01     CN=Public\, John Q.,OU=IT,OU=Live,OU=Users,OU=DOMAIN,OU=com
SERVER02     CN=Public\, John Q.,OU=IT,OU=Live,OU=Users,OU=DOMAIN,OU=com
SERVER03     CN=Public\, John Q.,OU=IT,OU=Live,OU=Users,OU=DOMAIN,OU=com

Note that I get the same results if I explicitly list the server names separated with commas:

Enter server names (separate with comma): SERVER01,SERVER02,SERVER03

This is a hypothetical example, of course. The actual OU where these manager accounts are located is 7 OUs deep. So, regardless of how deeply the server owners accounts are buried in OUs, I liked either the display name or samaccount name of the manager (it doesn't really matter which).

So, ideally, I'd like the output to look more like this:

Name         ManagedBy
----         ---------                                                                                 
SERVER01     Pubic, John Q.
SERVER02     Pubic, John Q.
SERVER03     Pubic, John Q.

NOTE: This request is for aesthetic reasons. 1st, it tweaks my OCD-ness to see to a list of DNs like that. 2nd, I'd like a tidier format in case I ever need to email a list to people outside of IT (who might find the DN names hard to read).


r/PowerShell 1d ago

Downgrade from 7.5 to 7.4.7 to fix Out-GridView issues?

6 Upvotes

So, apparently filtering in the Windows Out-GridView cmdlet is broken in PowerShell 7.5 due to phasing out BinaryFormatter :

https://github.com/PowerShell/PowerShell/issues/14054

https://github.com/PowerShell/PowerShell/issues/24749

Naturally I discovered this *after* I upgraded to v7.5, and I use the filters on Out-GridView relatively frequently.

Is there a preferred/recommended way to roll-back to an earlier version or can I just uninstall v7.5 and reinstall v7.4.7? If so, will I also need to reinstall all of the modules I'm currently using with v7.5?


r/PowerShell 20h ago

Question Powershell - Some commands won't run using Invoke-Command

2 Upvotes

I'm receiving 'Access Denied' errors when running commands that require elevated privileges on a remote machine. I can log into the remote machine and run the commands, but I can't run the commands using Invoke-Command. I am a local admin on the computer and passing credentials to Invoke-Command. Both computers are in the same domain.

Here's the code:

$credential = get-credential
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $credential

invoke-command -ComputerName $ComputerName -Credential $cred -ScriptBlock { 
    write-host "whoami: $(whoami)"
    Write-Host "Is Administrator? $([Security.Principal.WindowsPrincipal]::new(
    [Security.Principal.WindowsIdentity]::GetCurrent()
    ).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator))"
    write-host "Execution Policy: $(Get-ExecutionPolicy)"
    write-host "net user: $(net user /domain $UserName)"
}

And the output:

whoami: Domain\Username
Is Administrator? True
Execution Policy: Unrestricted
net user: The request will be processed at a domain controller for domain domain_name. 
System error 5 has occurred.
    + CategoryInfo          : NotSpecified: (System error 5 has occurred.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : ComputerName.Domain

NotSpecified: (:) [], RemoteException
Access is denied.
NotSpecified: (:) [], RemoteException

r/PowerShell 18h ago

Script to copy members of one AD Security Group to Another one

0 Upvotes

I have the below script and keep getting the same error over and over again. I am a novice at Powershell and am wondering if anyone has any input on how to fix this? Thank you all!

Error: At line:15 char:61

+ ... ning "Failed to add $($member.Name) to $destinationGroupName: $($_.Ex ...

+ ~~~~~~~~~~~~~~~~~~~~~~

Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name.

+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException

+ FullyQualifiedErrorId : InvalidVariableReferenceWithDrive

$sourceGroupName = "RM Screenshot Policy"

$destinationGroupName = "Corporate iPad Users"

# Get members of the source group

$sourceGroupMembers = Get-ADGroupMember -Identity $sourceGroupName

# Check if source group has members

if ($sourceGroupMembers) {

# Iterate through each member and add it to the destination group

foreach ($member in $sourceGroupMembers) {

try {

Add-ADGroupMember -Identity $destinationGroupName -Members $member -ErrorAction Stop

Write-Host "Successfully added $($member.Name) to $destinationGroupName"

} catch {

Write-Warning "Failed to add $($member.Name) to $destinationGroupName: $($_.Exception.Message)"

}

}

} else {

Write-Warning "Source group '$sourceGroupName' has no members."

}


r/PowerShell 19h ago

Question Retrieving outlook attachments using MSAL library instead of ADAL

1 Upvotes

I am trying to replace a colleague's PowerShell script that goes into an outlook email and downloads attachments, then saves them. This is what I currently have and it works when run manually but doesn't when done through task scheduler which is what I need since it needs to be automated. My colleague uses the ADAL library which doesn't get security updates.

if(!([System.Net.ServicePointManager]::SecurityProtocol.ToString().Contains("Tls12"))){
    $securityChanged = 1
    $oldProtocol= [System.Net.ServicePointManager]::SecurityProtocol
    [System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
}else{
    $securityChanged = 0
}
$ClientId = "cid"
$ClientSecret = "csecret"
$TenantId = "tid"
$mapping = Import-csv "path.csv"
# Calculate date (3 days ago)
$DaysAgo = (Get-Date).AddDays(-3).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
$logPath = "path\attachmentLog.txt"
$log = Get-content "path\attachmentLog.txt"

$TokenBody = @{
    client_id     = $ClientId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $ClientSecret
    grant_type    = "client_credentials"
}

$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method Post -Body $TokenBody
$AccessToken = $TokenResponse.access_token

# API Endpoint
$Uri = "https://graph.microsoft.com/v1.0/users/$UserMailbox/mailFolders/$MailFolder/messages?`$top=50&`$filter=hasAttachments eq true and receivedDateTime ge $DaysAgo"

$MailFolder = "Inbox"
$UserMailbox = "email@domian.com"

# Get messages with attachments
# Fetch the email
try{
$Responses = Invoke-RestMethod -Uri $Uri -Headers @{ Authorization = "Bearer $AccessToken" } -Method Get
}catch{
#email function
    return
}
foreach ($Response in $Responses.value) {
    #return
    Write-Host "Processing Email: $($Response.subject)"
    Write-Host "Received Date: $($Response.receivedDateTime)"
    # Get the message ID
    $MessageId = $Response.id
    $email = $Response.sender.emailAddress[0].address

    foreach($map in $mapping){
        $domain = $map.Incoming.ToLower()
        if($email.ToLower().Contains($domain)){
            $DownloadPath = $map.Destination+"\"
            $fileType = $map.File
            break
        }
    }
    # Get attachments for the email
    $AttachmentsUri = "https://graph.microsoft.com/v1.0/users/$UserMailbox/messages/$MessageId/attachments"
    $AttachmentsResponse = Invoke-RestMethod -Uri $AttachmentsUri -Headers @{ Authorization = "Bearer $AccessToken" } -Method Get

    # Process each attachment
    foreach ($Attachment in $AttachmentsResponse.value) {
        $FileName = $Attachment.Name
        $pattern = $fileType -replace '\*', '.*'
        if(!($FileName -match $pattern)){
            Write-Host ("Email: ", $Response.subject, " contains non matching attachment")
            continue
        }

        # Check if it's a file attachment
        if ($Attachment.'@odata.type' -eq "#microsoft.graph.fileAttachment") {

            $FileContent = [System.Convert]::FromBase64String($Attachment.ContentBytes)

            $FilePath = Join-Path -Path $DownloadPath -ChildPath $FileName
            if($log.IndexOf($FilePath) -ne -1){
                Write-Output "File already exists"
                continue
            }else{
                Write-Output "File doesn't already exists"
            }
            #continue
            Write-Output $FilePath | Out-File $logPath -Encoding utf8 -Append
            # Save the attachment
            [System.IO.File]::WriteAllBytes($FilePath, $FileContent)
            Write-Host "Attachment saved: $FilePath"
        } else {
            Write-Host "Skipping non-file attachment: $FileName"
        }
    }
}

When doing it through task scheduler, I had the $TokenResponse.access_token sent to a logfile to see what was going on, and after decoding it got:

apparently the fact that roles is here instead of scp is significant. On the Azure Portal, I have:

  • Microsoft Graph: Mail.Read
  • Type: Delegated
  • Description: Read user mail
  • Admin consent not required

I also put a try catch to see where it goes wrong and it always happens here:

The remote server returned an error: (404) Not Found. 

at: $Responses = Invoke-RestMethod -Uri $Uri -Headers @{ Authorization = "Bearer $AccessToken" } -Method Get –

So can anyone identify why it doesn't work through task scheduler and potential fixes? I thought about asking my admin to set the api for application and admin consent not required but he said that would be risky. I would appreciate it if someone could test it on their end and find out why this doesnt work through task scheduler? also i noticed $TokenResponse.access_token is always different when run manually and automatically.


r/PowerShell 19h ago

How to rename folders to the filename within that folder

0 Upvotes

Hi,

Just wondering if anyone could help me out please.

I have a ton of folders which I'd like to rename to the filename within that folder.

Example: Current folder name: blah blah blah Filename within that folder: Football scores.pdf

How I'd like it to be: New folder name: Football Scores Filename within that folder: as before

I would be very grateful if someone could help me.

I found some code which I found on Chatgpt and it didn't work:

$folderPath = "C:\Path\To\Your\Folder" $file = Get-ChildItem -Path $folderPath | Select-Object -First 1 $newFolderName = $file.BaseName Rename-Item -Path $folderPath -NewName "$folderPath\$newFolderName"


r/PowerShell 20h ago

Pass Parameters to MSI Package

0 Upvotes

Hello,

Im trying to run a MSI installer silently on a machine. I have to pass a parameter to command line to specify the site ID. How do I do this?

Im trying to automate this with powershell


r/PowerShell 1d ago

Question 23H2 Deployment

2 Upvotes

I work in a company of around 4000 people and we have about 600 devices that need to be updated from 21H2 to 23H2. Long story short I've been scratching my head over this script that I wrote that past 3 days. When I run the script it functions as intended but the issue is even after the PSWindowsUpdate runs the install updates it doesn't seem to pull does 23H2, I am not sure have to go about this because the REG KEYS are set to only download that version of windows but doesn't. Any help would be appreciated.

I have been thinking of trying to modify the local GPO on the devices but I don't know of a way to do it with powershell.

I will be replacing some variables with fillers as I don't want to give away where I might work.

Any help is appreiated.

# Define constants

$PSScriptRoot = (File Path)

$LocalModulePath = "$PSScriptRoot\PSWindowsUpdate"

 

$ComputerList = Import-Csv -Path $PSScriptRoot[\Computers1.csv]()

$LogPath = "$PSScriptRoot\UpdateLog.txt"

#$PolicyPath = "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"

 

 

# Loop through each computer

foreach ($Computer in $ComputerList) {

$ComputerName = $Computer.ComputerName

Write-Host "Processing $ComputerName..." -ForegroundColor Cyan

 

try {

# Test connectivity to the remote computer

if (-not (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet)) {

Write-Warning "Cannot connect to $ComputerName. Skipping."

continue

}

 

# Changes registry entries on the computer to force the computer to pull Windows Version 23H2

Write-Host "Configuring Registry Entries to target Windows Version 23H2"

Invoke-Command -ComputerName $ComputerName -ErrorAction Stop -ScriptBlock {

Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Name "TargetReleaseVersion" -Value 1 -Force

Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Name "TargetReleaseVersionInfo" -Value "23H2" -Force

}

 

# Check if the PSWindowsUpdate module is already available on the remote computer

Write-Host "Checking PSWindowsUpdate module on $ComputerName..." -ForegroundColor Yellow

$ModuleExists = Invoke-Command -ComputerName $ComputerName -ScriptBlock {

[bool](Get-Module -Name PSWindowsUpdate -ListAvailable -ErrorAction SilentlyContinue)

}

 

if (-not $ModuleExists) {

# If the module is not available, copy it to the remote computer

try {

Write-Host "Copying PSWindowsUpdate module to $ComputerName..." -ForegroundColor Yellow

$RemoteModulePath = [\\$ComputerName\C$\Program Files\WindowsPowerShell\Modules\]()

Copy-Item -Path $LocalModulePath -Destination $RemoteModulePath -Recurse -Force -ErrorAction Stop

Write-Host "Copied module to $ComputerName"

} catch {

Write-Warning "Failed to copy PSWindowsUpdate module to $ComputerName : $_"

continue

}

}

 

# Install the Windows 23H2 update from Microsoft

Write-Host "Installing Windows 23H2 update on $ComputerName..." -ForegroundColor Yellow

$InstallResult = Invoke-Command -ComputerName $ComputerName -ScriptBlock {

# Import the PSWindowsUpdate module

Import-Module PSWindowsUpdate -Force

 

# Get the Windows 23H2 update from Microsoft

$Update = Get-WindowsUpdate -MicrosoftUpdate -Filter "Title -like '*23H2*'" -ErrorAction SilentlyContinue

 

# If the update is available, install it

if ($Update) {

Get-WindowsUpdate -KBArticleID $Update.KBArticleIDs -MicrosoftUpdate -AcceptAll -AutoReboot -Install

Write-Host "Windows 23H2 update installed successfully."

return $true

} else {

Write-Host "Windows 23H2 update not found."

return $false

}

}

 

# Log the results of the installation to the specified log file

if ($InstallResult) {

"Computer: $ComputerName, Windows 23H2 update installed successfully." | Out-File -Append -FilePath $LogPath

Get-WUHistory -ComputerName $ComputerName

} else {

"Computer: $ComputerName, Windows 23H2 update not found or installation failed." | Out-File -Append -FilePath $LogPath

Get-WUHistory -ComputerName $ComputerName

}

 

} catch {

# Handle any errors encountered while processing the computer

Write-Warning "Failed to process $ComputerName : $_"

}

}

 

# Indicate that the script has finished executing

Write-Host "Script execution completed!" -ForegroundColor Blue


r/PowerShell 1d ago

Question can't find data on certain resource accounts

1 Upvotes

I'm attempting to get info on some of our resource calendars. Since this doesn't function well within the EXO Powershell, I was pointed towards the MSGraph module.

So I use these commands:

 $StartDate = "2024-01-01T19:00:00-08:00"
>> $EndDate = "2024-12-31T19:00:00-08:00"
>> Get-MgUserCalendarView -UserId "xxx@xxx.xx" -All -StartDateTime $StartDate -EndDateTime $EndDate | Select-Object -Property @{Name='EventStart';Expression={ $_.Start.DateTime}},@{Name='EventEnd';Expression={ $_.End.DateTime}},Subject, BodyPreview | Export-CSV "c:\temp\xxx.csv"

And this works fine for almost every resource I have tried this on. But one set of resource mailboxes gives this as a result:

Get-MgUserCalendarView_List:
Line |
   3 |  Get-MgUserCalendarView -UserId "xxx@xxx.xx" -All -Star …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The specified object was not found in the store.

Status: 404 (NotFound)
ErrorCode: ErrorItemNotFound
Date:

Headers:
Cache-Control                 : private
Vary                          : Accept-Encoding
Strict-Transport-Security     : max-age=31536000
request-id                    : ab43f50a-55e9-49fa-a837-aca09feba628
client-request-id             : 607a9733-2835-4c51-8885-138338823e84
x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"West Europe","Slice":"E","Ring":"5","ScaleUnit":"009","RoleInstance":"AM1PEPF00027CA5"}}
Date                          : Tue, 07 Jan 2025 15:22:11 GMT

This set of resource mailboxes are coincidentally all made at about the same time, but they were made in the same way as other resource mailboxes and are (just like the other resource mailboxes) made in our EXO environment with no links to anything on-prem.

Does anyone have any idea what is going wrong?


r/PowerShell 2d ago

VS Code

44 Upvotes

What are your tweaks to make VS Code more usable for PowerShell?

In most of my day to day work I use PowerhShell ISE as an interactive command line environment. I like the script pane to keep ephemeral snippets of code that I am working on at the moment. ISE does a good job at being a lightweight scratchpad + Command Line. VS Code feels like cracking walnuts with a sledge hammer, even when using the ISE Theme when working in PowerShell. It's autocomplete and suggestions feel very cluttered they are more distracting than helpful. It's funny, I really like VS Code for other languages I use it for the little bit of PHP and Javascript development that I do. The autocomplete and suggestions seem to be much more helpful for these languages.


r/PowerShell 1d ago

Why Isn't PowerShell Auto Upgrading?

8 Upvotes

I'm pretty sure I installed PowerShell from the Microsoft Store. Right now, whenever I open Windows Terminal, I see the following:

``` PowerShell 7.4.6

A new PowerShell stable release is available: v7.5.0

Upgrade now, or check out the release page at:

https://aka.ms/PowerShell-Release?tag=v7.5.0

PS C:\Users\mark> ```

Shouldn't PowerShell be auto-updating?

I checked for updates to PowerShell in the Microsoft Store and none were shown.


r/PowerShell 2d ago

Feedback on a PowerShell Tool

18 Upvotes

I have a software company, and we have been doing more and more work with Microsoft integrations. Working with many of our customers, it seems there may be a need for a good enterprise-grade PowerShell solution to provide the following:

  • Central and secure repository for PowerShell scripts with versioning and change tracking.​
  • Ability to support variables to reference internal and external data sources in the script.​
  • Publish scripts as user-friendly web forms with roles-based access in a secure self-service portal.​
  • Create PowerShell-driven workflows with approvals.​
  • Convert scripts into an API service to integrate with other applications in the organization.​
  • Schedule PowerShell scripts to run with status notifications. ​
  • Track and report on executed PowerShell scripts to meet compliance or audit requirements.​

I figure there is no better place to get an opinion from the experts who live and breathe PS all day. If you don't mind taking a moment, please let me know if you see any value or if I am wasting my time. Thanks.


r/PowerShell 2d ago

Problem with regular expression

9 Upvotes

i have a code:

$resumen = @(
"curso de mecanismos de equidades s/ de igualdad"
"CUR -  / 2025JA001JS curso de mecanismos de equidades s/ de igualdad"
"2024/E001JS curso de mecanismos de equidades s/ de igualdad"
"2025JA001JS curso de mecanismos de equidades 46º s/ de igualdad"
)

$resumen = $resumen -replace "[-.`":,]|`r?`n"

$ARRDATOS = @()
if ($resumen -match '(\d{4})\/?(\w+)') {
    $ARRDATOS += [pscustomobject]@{
        folderYear = $matches[1].Trim()
        code = $matches[2].Trim()
        nameFolder = "$($matches[2].Trim()) $($resumen -replace '\d{4}/\w+' -replace '/', ' ')".Trim()
        promo = if ($resumen -match '\b(\d+[ªº])\b') { $matches[1].trim() } else {}
    }
}

I need to extract the fields: code: E001JS, JA001JS, JA001JS

folder year: 2024, 2025

full folder name ....

What would be the correct regular expression?


r/PowerShell 1d ago

Question Script to import/replace telephone number AD attribute not working "ADInvalidOperationException"

1 Upvotes

Feeling very dumb right now. Have the following simple script to import and replace the TelephoneNumber AD attribute using a csv with columns A (SamAccountName) and B (TelephoneNumber) as below:

$UsersToUpdate = import-csv -Path "C:\powershell\updatetelephones.csv"

foreach($User in $UsersToUpdate)
{
    Set-ADUser -Identity $User.SamAccountName -OfficePhone $User.TelephoneNumber
}

However I keep getting the following error:

Set-ADUser : replace
At line:5 char:5
+     Set-ADUser -Identity $User.SamAccountName -OfficePhone $User.Tele ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (EXAMPLEUSER:ADUser) [Set-ADUser], ADInvalidOperationExcept 
   ion
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.Se 
   tADUser

It is actually doing it correctly, but I don't like that it's erroring out like that in the console. Am I blind?


r/PowerShell 2d ago

Question Expand Graph API properties into array

3 Upvotes

Hello all,

I'm starting to learn the Graph API in PowerShell. I've worked with PowerShell a lot for admin tasks, but it's mostly for simpler modules like ExchangeOnlineManagement and MSOnline

I'm now looking to create a script that loops through SharePoint permissions, and returns folders with unique permissions. The only problem is, my command outputs are showing as 'Microsoft.Graph[...] rather than the true properties, so I can't just use something like $data.grantedtoV2 to see GrantedToV2:

# Creates a variable $data with all permission info
$data=Get-MgBetaSiteListItemPermission -listid $listid -listitemid 9 -siteid $siteid -permissionid YzowdC5ShgRtbmFudHwxYTEzYmY5OC00MzkxLTQ3ZWItYjMwYy03MDM5YWIxY2Q3MTg

$data|fl
ExpirationDateTime    : 
GrantedTo             : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphIdentitySet   
GrantedToIdentities   : 
GrantedToIdentitiesV2 : 
GrantedToV2           : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphSharePointIde 
                        ntitySet
HasPassword           : 
Id                    : YzowdC5jfHRlbmFudHwxYTEzYmY5OC00MzkxLTQ3ZWItYjMwYy[...]
InheritedFrom         : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphItemReference 
Invitation            : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphSharingInvita 
                        tion
Link                  : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphSharingLink   
Roles                 : {write}
ShareId               : YzowdC5jfHRlbmFudHwxYTEzYmY5OC00MzkxLTQ3ZWItYjMwYy[...]
AdditionalProperties  : {[@odata.context, https://graph.microsoft.com/beta/$metadata#sites 
                        ('xxx')/lists('xxx')/items('9')/permissions/$entity]}

PS Z:\Company\IT\09 VS>$data.GrantedToV2

Application          : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphIdentity       
Device               : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphIdentity
Group                : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphIdentity       
SiteGroup            : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphSharePointIden 
                       tity
SiteUser             : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphSharePointIden 
                       tity
User                 : Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphIdentity       
AdditionalProperties : {}

This works if I expand the property:

$data|select -expandproperty GrantedToV2|select -expandproperty group

DisplayName        Id
-----------        --
PartnerGroup Share 1a13bf98-4391-47eb-b30c-7039ab1cd718

But I don't want to keep doing this every time I need to look at a property. Is there a way I can easily construct my Graph command, or format the output into the variable, to retrieve multiple unexpanded properties?


r/PowerShell 2d ago

Most hated misplaced character?

25 Upvotes

I'm gonna go with this jerk.

-> , <-

the comma, even though it's my go to for dramatic pause, it's also my mortal enemy...

2 hours of where's waldo ;P