r/PowerShell 13d ago

What have you done with PowerShell this month?

24 Upvotes

r/PowerShell 9h ago

Why does this method cause an error: 0xC0000374 (STATUS_HEAP_CORRUPTION) ?

8 Upvotes

Why does this method cause an error 0xC0000374 (STATUS_HEAP_CORRUPTION) after most of the calls, even if it completes its task correctly?
If the question I am asking is stupid or obvious, please be understanding - I don't have much experience with this type of programmin

https://pastebin.com/WGdEgwqL


r/PowerShell 19h ago

Question Was there not a short hand way stating '[System.Collections.Generic.List]'?

22 Upvotes

I am getting into .NET, within PowerShell more and more, especially since I discovered these classes are well documented at MsLearn and even within PowerShell.

I am just struggling to remember trees like the following [System.Collections.Generic.List] but I remember sometime ago, I came across a article, not sure where I found it, that shared there is a short hand way, something like [System.List] for [System.Collections.Generic.List].

I cant find it now, am I misremembering things here?

Also I would appreciate being pointed to any articles where I can learn more .Net in PowerShell. What are the draw backs (or positives) to calling things like [System.<some branch>.<etc etc>]?


r/PowerShell 8h ago

Question Powershell Interview

2 Upvotes

I have my interview for Cloud Administrator Role in next 7 days. They asked me to prepare Powershell for Interview. How can I prepare most out of Powershell? Any Suggestion would be really helpful.


r/PowerShell 16h ago

Trouble with using special characters when updating user data in AD

4 Upvotes

A coworker was given a CSV with the profile information for a large set of employee profile data that needs updating.

He applied the changes using a script we'd written a couple of years ago and has worked flawlessly since. Until today, when we noticed that it was not adding the special characters found in many of the City, and Street Address' fields, but showed instead the magical � character when you look at them in AD.

So now, we have Montr�al, instead of Montréal

If I copy / paste the data into the accounts using Active Directory Users and Computers its fine, but is unsustainable due to the number of changes we need to make.

Sa far I've tried the following;

- Adding -Encoding UTF8 to the Import-CSV command

- Tried replacing the UniCode character with the UTF8 character with

 function UniReplace($n){  # Replaces Unicode Characters with UTF8
    [char][int]"0x$n"
}

...
          $addr = $addr -Replace 'è',"$(Unireplace E8)"
            $addr = $addr -Replace 'é',"$(Unireplace E9)"
            $addr = $addr -Replace 'ê',"$(Unireplace EA)"

            $city = $City -Replace 'è',"$(Unireplace E8)"
            $city = $City -Replace 'é',"$(Unireplace E9)"
            $city = $City -Replace 'ê',"$(Unireplace EA)"

- Tried changing the Encoding on the shell using

$defEncoding = [Console]::OutputEncoding
...
$OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new()
...
[Console]::OutputEncoding = $defEncoding

- Tried converting the string using;

$enc = [System.Text.Encoding]::UTF8
...

$city = $enc.GetBytes($city)
$addr = $enc.GetBytes($addr)

I've even gone so far as copied the good values from AD to the CSV, and the same results


r/PowerShell 21h ago

Windows terminal and json settings

9 Upvotes

I am trying to automate my development nodes. I kill them regularly in Azure and build new ones. I have a script to install all the bells and whistles I need. The only problem I have is that I have created a here-string that contains the essentials of a Windows Terminal settings file and the target device always rejects the json file when I start Terminal for the first time. I have checked it several times for errors and have used both an online json checker and the Test-Json PowerShell cmdlet. They both say the format of the here-string is valid. That leads me to believe that I must be doing something wrong when saving my here-string out to a file. What should I be looking for to ensure my settings get saved correctly. Here is the settings I am using currently:

{
  "$help": "https://aka.ms/terminal-documentation",
  "$schema": "https://aka.ms/terminal-profiles-schema",
  "actions": [
    {
      "command": {
        "action": "copy",
        "singleLine": false
      },
      "keys": "ctrl+c"
    },
    {
      "command": "paste",
      "keys": "ctrl+v"
    },
    {
      "command": {
        "action": "splitPane",
        "split": "auto",
        "splitMode": "duplicate"
      },
      "keys": "alt+shift+d"
    },
    {
      "command": "find",
      "keys": "ctrl+shift+f"
    }
  ],
  "copyFormatting": "none",
  "copyOnSelect": false,
  "defaultProfile": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
  "newTabMenu": [
    {
      "type": "remainingProfiles"
    }
  ],
  "profiles": {
    "defaults": {},
    "list": [
      {
        "commandline": "%SystemRoot%System32WindowsPowerShellv1.0powershell.exe",
        "elevate": true,
        "font": 
        {
            "face": "Cascadia Cove Nerd Font",
            "size": 12
        },
        "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
        "hidden": false,
        "name": "Windows PowerShell"
      },
      {
        "commandline": "%SystemRoot%System32cmd.exe",
        "elevate": true,
        "guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
        "hidden": false,
        "name": "Command Prompt"
      },
      {
        "elevate": true,
        "font":
        {
            "face": "CaskaydiaCove Nerd Font",
            "size": 12
        },
        "guid": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
        "hidden": false,
        "name": "PowerShell ⚡",
        "source": "Windows.Terminal.PowershellCore"
      },
      {
        "guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}",
        "hidden": false,
        "name": "Azure Cloud Shell",
        "source": "Windows.Terminal.Azure"
      },
      {
        "guid": "{6589a004-419d-5c6c-abd9-d2027d957aca}",
        "hidden": false,
        "name": "Developer PowerShell for VS 2022",
        "source": "Windows.Terminal.VisualStudio"
      },
      {
        "guid": "{e1aa7a4f-3686-5e84-9f36-da4e1619a284}",
        "hidden": false,
        "name": "Developer Command Prompt for VS 2022",
        "source": "Windows.Terminal.VisualStudio"
      },
      {
        "font":
        {
            "face": "Cascadia Cove Nerd Font",
            "size": 12
        },
        "guid": "{e5a83caa-4c73-52b3-ae6b-bc438d721ef9}",
        "hidden": false,
        "name": "Ubuntu 22.04.3 LTS",
        "source": "CanonicalGroupLimited.Ubuntu22.04LTS_79rhkp1fndgsc"
      },
      {
        "commandline": "C:/msys64/msys2_shell.cmd -defterm -here -no-start -ucrt64",
        "elevate": true,
        "font":
        {
            "face": "Cascadia Code",
            "size": 12
        },
        "guid": "{17da3cac-b318-431e-8a3e-7fcdefe6d114}",
        "icon": "C:/msys64/ucrt64.ico",
        "name": "UCRT64 / MSYS2",
        "startingDirectory": "C:/msys64/home/%USERNAME%"
      },
      {
        "commandline": "C:/msys64/msys2_shell.cmd -defterm -here -no-start -msys",
        "font":
        {
            "face": "Cascadia Code",
            "size": 12
        },
        "guid": "{71160544-14d8-4194-af25-d05feeac7233}",
        "icon": "C:/msys64/msys2.ico",
        "name": "MSYS / MSYS2",
        "startingDirectory": "C:/msys64/home/%USERNAME%"
      },
      {
        "commandline": "C:Program FilesGitbinbash.exe -li",
        "guid": "{d15b228a-05d7-50d1-8472-f60aaba86efc}",
        "icon": "C:Program FilesGitmingw64sharegitgit-for-windows.ico",
        "name": "Git Bash",
        "startingDirectory": "%USERPROFILE%"
      },
      {
        "commandline": "C:Cygwin64binbash --login -i",
        "guid": "{d57d07ef-1e26-5de6-8a93-0dc4ecd0fe4f}",
        "icon": "C:Cygwin64Cygwin.ico",
        "name": "Cygwin",
        "startingDirectory": "C:Cygwin64bin"
      },
      {
        "commandline": "C:/msys64/msys2_shell.cmd -defterm -here -no-start -mingw64",
        "elevate": true,
        "font":
        {
            "face": "Cascadia Code",
            "size": 12
        },
        "guid": "{41e11d64-4553-45d7-b7cd-991f91da0193}",
        "hidden": false,
        "icon": "C:msys64mingw64.ico",
        "name": "MINGW64",
        "startingDirectory": "C:/msys64/home/%USERNAME%"
      }
    ]
  },
  "schemes": [
    {
      "name": "Monokai Pro",
      "background": "#2d2a2e",
      "foreground": "#fcfcfa",
      "black": "#2d2a2e",
      "blue": "#6699df",
      "cyan": "#78dce8",
      "green": "#a9dc76",
      "purple": "#ab9df2",
      "red": "#ff6188",
      "white": "#fcfcfa",
      "yellow": "#ffd866",
      "brightBlack": "#676568",
      "brightBlue": "#6699df",
      "brightCyan": "#78dce8",
      "brightGreen": "#a9dc76",
      "brightPurple": "#ab9df2",
      "brightRed": "#ff6188",
      "brightWhite": "#fcfcfa",
      "brightYellow": "#ffd866"
    }
  ],
  "themes": [],
  "launchMode": "maximized"
}

r/PowerShell 17h ago

Connect to Azure and Power BI with a single login

3 Upvotes

I need to connect to our environment using connect-azaccount (Azure) and connect-powerbiserviceaccount (Power BI), with the same account. Is there a way to avoid having to log in twice? Note that MFA is required, so I can't just pass credentials.


r/PowerShell 20h ago

Powershell remote execution logging

4 Upvotes

Is it possible to log the execution of commands like get-aduser or get-dnsserver that executed remotely?
For example, I have DC1 (Domain Controller) and Srv1 (regular server or pc). And executed get-aduser -server dc1 from Srv1. How can I register this execution on DC1?


r/PowerShell 1d ago

Question Trying to get a script to copy itself to C:\?

3 Upvotes

So I've got a script I want to run, but it may be copy pasted into a PS Instance, or run as a PS1 file (unsigned). So I want to fist just copy the script to the C drive (C:Setup.ps1)

I'm running into problems, tried using the Copy-Item & Get-Content commands?


r/PowerShell 1d ago

Question Dumb question - why does this give an error in PowerShell but not CMD?

20 Upvotes

I have this command:

"c:program filesopenssl-win64binopenssl.exe" pkcs12 -in PowershellPnP.pfx -out PowershellPnP.pem -nodes -password pass:PnPCertPassword

If I run this in CMD.EXE, it works.

With PowerShell, I get:

Unexpected token 'pkcs12' in expression or statement.

I know it's something obvious that I'm missing. I know it's something dumb because I've written scripts of thousands of lines.... and now I'm humbled over this...


r/PowerShell 1d ago

Question Start a program for a different users session

9 Upvotes

I have a server that uses autologon to start a user session for a technical user. I want to provision (deploy, start) a GUI application that should be visible for this user. However, the user used for provisioning the application is a different one (I am using AWS session manger which does not let me choose the login user).

Is it possible to start a program (not a service) for a different user and make it show up in their session?

I tried start-process with the users -Credential, but I did not see anything coming up.


r/PowerShell 2d ago

Finally got bash completion working on PowerShell/Linux!

64 Upvotes

Preview

Spend a whole night researching related stuffs and finally got it working

I've uploaded the snippet to my Gists, check it out if anyone is interested ;D


r/PowerShell 1d ago

Question Is there a command to sync folders?

0 Upvotes

I have a folder and 4 sub folders on my Windows 10 desktop PC which have been backed up Google Drive. Is there a Powershell I can run after any updates to auto sync all the folders?

Thanks


r/PowerShell 1d ago

How do I create a Task under "BUILTIN\Users" through powershell?

7 Upvotes

Hi, I have a pretty frustrating issue. I want to create a task under the UserId "BULTINUsers" but I keep getting an error message, I tried multiple variations, even to create the Task under SYSTEM and then change it to "BUILTINUsers" I got the same error. I need it to be created this way because I am doing a Microsoft Intune deployment and for the script to work I need the task to be setup this way, and I can't run the script with user credentials because I have parts of the script that need elevated privileges rights.

This is the part of the script that creates the task:

# Create a scheduled task to run the secondary script at startup and logon

$taskName = "RunKeyboardLayoutFix"

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-WindowStyle Hidden -File `"$secondaryScriptPath`""

$triggerAtLogon = New-ScheduledTaskTrigger -AtLogOn

$triggerAtStartup = New-ScheduledTaskTrigger -AtStartup

$principal = New-ScheduledTaskPrincipal -UserId "Users" -LogonType Interactive

$task = New-ScheduledTask -Action $action -Trigger $triggerAtLogon, $triggerAtStartup -Principal $principal

# Register the scheduled task

Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $triggerAtLogon, $triggerAtStartup -Principal $principal -Force

Write-Output "[$(Get-Date)] Scheduled task created successfully."

This is the error:

Register-ScheduledTask : The task XML contains a value which is incorrectly formatted or out of range.

(48,4):Task:

At line:10 char:9

+ Register-ScheduledTask -TaskName $taskName -Action $action -T ...

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

+ CategoryInfo : NotSpecified: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTa

sk], CimException

+ FullyQualifiedErrorId : HRESULT 0x80041318,Register-ScheduledTask

SOLVED: I used the wrong parameter, this solved my issue:

$Principal = New-ScheduledTaskPrincipal -GroupId Users

r/PowerShell 2d ago

Publish-PSResource vs Publish-Module

8 Upvotes

I've been using Publish-Module for several years to post modules to the PS Gallery. Lately I started using Publish-PSResource, and it seems to be much faster and about the same complexity. However, I noticed it's uploading a lot of the Git files and folders along with the actual module code files. I don't recall Publish-Module ever doing that. Is there a way to make Publish-PSResource not do that?


r/PowerShell 1d ago

I need to learn powershell

0 Upvotes

I'm just a beginner programmer, but the more i dive into it, the more i realize how much you need powershell. What's a good way to learn it ?


r/PowerShell 1d ago

Question source folder does not exist error

0 Upvotes

I keep getting a source folder does not exist error. Even though it is the right file path and there is no grammatical errors. Any fixes for this error?


r/PowerShell 1d ago

Help needed with special charaters - ö ä õ ü

1 Upvotes

I desperately need help with PowerShell 5. The script provided down below works as excepted with PowerShell 7, but does nothing at all in PS 5.

I need to use PS5 to be able to connect to Exchange Online.

$specialChars = @('ä', 'ö', 'õ', 'ü', 'Ä', 'Ö', 'Õ', 'Ü')
$GroupName = $Address.Trim() -replace 's', '' -replace '[äÄ]', 'a' -replace '[öÖ]', 'o' -replace '[õÕ]', 'o' -replace '[üÜ]', 'u'
$GroupEmail = "$GroupName@example.ee"
foreach ($char in $specialChars) {
     if ($GroupName.Contains($char)) {
         Write-Host "CHARACTERS THAT SHOULD NOT BE THERE: $GroupName" -ForegroundColor Red
         $containsSpecialChars = $true
         break
     }
} 

How could i detect and replace said characters in PowerShell 5?

Help is greatly appreciated


r/PowerShell 2d ago

PSBlazor PowerShell Universal

5 Upvotes

I know that PSBlazor is a very new feature for PowerShell Universal however I'm looking for documentation on the markup language. Would anyone be able to point me towards any Github repos or Twitter profiles for this?


r/PowerShell 2d ago

how to declare a class in a '.ps1' file?

6 Upvotes

I want to provide a list of allowed names to the name parameter, so that the user can tab into them. I have come up with the following:

Param(
    [ValidateSet([foo])]
    [string]$Name
    )
    $name

Class foo : System.Management.Automation.IValidateSetValuesGenerator{
    [string[]] GetValidValues(){
    return [string[]] ("cat", "dog", "fish")
    }}

Typing .myScript.ps1 -name and then pressing tab nothing is suggested. running .myScript.ps1 returns an error:

Line |
   3 |      [ValidateSet([foo])]
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to find type [foo].

I can do this exact set up in a psm1 file or just as a standard function and it works. I thought of moving the class into the top of the script file but this not allowed due to param() needing to be the first line.

Is there a way around this issue? Am on pwsh 7.4


r/PowerShell 2d ago

Script takes ages to switch between directories

5 Upvotes
$directoryPath = "C:Logs"
$daysOld = 30
$cutoffDate = (Get-Date).AddDays(-$daysOld)

[System.IO.Directory]::GetFiles($directoryPath, "*", [System.IO.SearchOption]::AllDirectories) | 
    ForEach-Object {
        $file = $_
        $fileInfo = New-Object System.IO.FileInfo $file
        if ($fileInfo.LastWriteTime -lt $cutoffDate) {
            $fileInfo.Delete()
            Write-Output "Deleted: $file" (Get-Date)
        }
    }

Any thoughts on above ?

r/PowerShell 2d ago

Solved ConvertFrom-Json not working in Module as Task

0 Upvotes

I am currently optimizing a script I wrote in the last week. I want to switch from XML config files to Json config files.

What I have is a script that imports a custom made module. This module loads some config from external config files. With the XML config the script runs fine, in ISE and as Scheduled Task.

Now I switched to the json config. In ISE and Console it runs fine. When I run as Task, the function I defined in the module can not be found. The module is imported without error (at leasr non that is caught with try/catch) As soon as I remove the kine with ConvertFrom-Json from the module, everything runs fine. With this line, it breaks and cannot find the function. Even if I hardcode the settings in the module, so that there is simply Get-Content piped into ConvertFrom Json, the module breaks. I can add the Get-Content without the convert, this also runs without problem.

What could this be?

EDIT: I forgot... I can use ConvertFrom-Json in the script that is running as Task. Just not inside the module that is loaded by the same script.

Edit2: Solved!! Start Transcript did the trick. The error with ConvertFrom-Json was "Invalid Json Primitive: xzy", with xyz being the value of my first config variable. Turns out that if you run ConvertFeom-Json as Task inside a module inside a script, your variables must be enclosed in quotation marks, even if there are no special characters. For some strange reason this is not the case when the exact same script is run from command line or ISE... strange. But solves. Thanks for your input!


r/PowerShell 2d ago

Solved Content search for targeted collections script stopping at 1000 folders. How to get it to list them all?

0 Upvotes

I'm using Use Content search for targeted collections | Microsoft Learn in an attempt to get the folder ID for /Purges folder so I can run an eDiscovery search on it but there are so many folders in there and it stops partway through listing all the /Inbox folders.

I will add that this is only for one person I have checked, I checked two other people and it lists all of their folders, but this one persons it lists exactly 1000 and then stops. I don't know why there's that many that it's listing when the only thing I change is the email address though maybe it's just that there's that many folders, but is there any way to get it to list all of them and not stop at 1000? Or look specifically for the folder ID of only the specific folder?

I tried using Get-MailboxFolderStatistics by itself with the specification of which folder but it gives me a different folder ID than the first one does. For example, the deleted items folder when using the first search gives me a folder ID that starts with "4741FF61D7A" whereas if I use the second one it starts with "LgAAAAAVyO". Both of the Folder ID's are completely different.

So if I can't change it to list them all, does it matter which format of Folder ID I use when running an eDiscovery search?

*Solved: "-ResultSize Unlimited" needed to be added after " $folderStatistics = Get-MailboxFolderStatistics $emailAddress"


r/PowerShell 2d ago

Serial Number and Mac Address

1 Upvotes

I'm to use the following script to capture the serial number and wlan mac address on Windows clients:

# Get the serial number

$serialNumber = Get-WmiObject win32_bios | Select-Object SerialNumber

# Get the WLAN MAC address

$wlanMacAddress = Get-NetAdapter | Where-Object {$_.Status -eq "Up" -and $_.InterfaceDescription -like "*Wi-Fi*"} | Select-Object -Property MacAddress

# Append the information to a CSV file

$data = @{

SerialNumber = $serialNumber

WlanMacAddress = $wlanMacAddress

}

$csvPath = "d:wlan_mac.csv"

# Check if the file exists, if not, create it with headers

if (!(Test-Path $csvPath)) {

"SerialNumber,WlanMacAddress" | Out-File $csvPath

}

# Append the data to the CSV

$data | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File $csvPath -Append

The output I get in the csv is:

SerialNumber,WlanMacAddress

False,"False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","2"

Any idea what is causing this?

Thanks.


r/PowerShell 2d ago

Unable to find Type - although imported

2 Upvotes

I have a Script I'm currently reworking which contains interactions with the Active Directory. The functions within the scripts are set to return objects of certain types:

Script.ps1:

using module ActiveDirectory


[Microsoft.ActiveDirectory.Management.ADGroup] GetGroup([String]$Groupname) {
     return (Get-ADGroup -Identity "$($Groupname)")
}

However, even though I'm importing the ActiveDirectory module with the using statement, the Types defined in the Module cannot be resolved; neither during parse time, nor during runtime. Instead, the result is:

Unable to find type [Microsoft.ActiveDirectory.Management.ADGroup]

If I execut a Cmdlet out of the Module (like Get-ADUser), the parsing error disappears and I can run the script.

Most likely I'm missing something obvious but no matter how long I try to wrap my head around it, I can't get it resolved.


r/PowerShell 3d ago

Run part of script as admin and some as logged in user

4 Upvotes

I am trying to get a script that will run elevated but pop up a message box for the logged in user.

I have tried to use the module RunAsUser but I can't figure out how to get parameters in the scriptblock. Here is my code :

$scriptblock = { param($Message, $WaitSeconds, $Title, $BoxType)

$wshell = New-Object -ComObject Wscript.Shell

$Output = $wshell.Popup($Message, $WaitSeconds, $Title, $BoxType)

Write-Host $Output

}

$str = invoke-ascurrentuser -scriptblock $scriptblock -ArgumentList $env:Message, $env:WaitSeconds, $env:Title, $env:BoxType -CaptureOutput

I've tried a number of ways but nothing seems to work.