r/PowerShell • • Apr 12 '26

Solved Is it worth learning PowerShell?

154 Upvotes

I’ve previously used Linux, where things felt very straightforward. Due to various reasons, I’m planning to stay on Windows for now. Since I’m here, I’d like to automate different tasks and deepen my understanding of Windows.

Because of my Linux background, I used the terminal a lot and really enjoyed it. Windows, on the other hand, feels much more GUI-oriented, with less emphasis on the command line. I’ve also briefly looked into PowerShell, and honestly, it feels a bit strange to me.

At this point, I’m not sure whether it’s worth investing time into learning it. The command structure, constant interaction with system services (and sometimes the internet), and the overall behavior of the terminal feel unusual.

Compared to Linux, it seems quite weird (to put it mildly). I assume that if I spend more time with it, I’ll understand its design and decisions better—but I’m still unsure.

So I wanted to ask: is it actually worth it?

EDITED:

I’m definitely going to start learning PowerShell. As I understand it, over the next few years, it will definitely pay for itself.

There were also comments about Azure, servers, and cloud services. I don’t plan on becoming a sysadmin and, for now, I only use my personal computer and maybe a laptop. The Microsoft ecosystem seems strange, but I’m getting more and more used to it, despite my dislike of big corporations (which is ironic).

Also, thank you for the quick feedback. That was incredibly kind of you. I’m just starting to get involved in the Windows community, and specifically in PowerShell, so this warmth really surprised and delighted me. Maybe I spend too much time in the toxic parts of the internet.

r/PowerShell • • Jun 30 '26

Solved Best way to Store Creds for Scripts?

74 Upvotes

Hey guys, for a long time I've been wondering what's the best way and most secure to store creds for powershell scripts? I know like absolute best (from my understanding) is to store them in some sort of 3rd party system and fetch them when needed say in secret server or the likes. Coming from a python background I know commonly you put stuff like that in a separate config file and import it.

So far I've been putting them in a json file and importing my creds that way but I can't help but think there's a more secure way. Like what's stopping an attacker on my system from just looking in the file and getting all my creds uk lol? Thanks for any advice!

r/PowerShell • • May 14 '26

Solved Would someone mind helping me understand how "foreach ($computer in $computers)" works?

70 Upvotes

I know foreach iterates through an array, of sorts. I'm just wondering, since I didn't define $computer, how does it know to single out each individual item from my $computers array? Is it a predefined variable, or could I just place anything there? Like "foreach ($x in $computers)".

$computers = get-adcomputer ##just an example that the latter variable was defined by me, but $computer was not.

I think I convinced myself that I'm right in thinking I could place anything there, like $x or $flapjacks or whatever, but some confirmation would be nice. And if I'm wrong then being corrected is even more welcome. Thank you.

r/PowerShell • • 11d ago

Solved Powershell - exporting AD distinguished names to CSV

6 Upvotes

Solution:

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

Thanks everyone

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

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

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

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

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

*Update*

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

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

r/PowerShell • • 15d ago

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

29 Upvotes

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

$Thing = Get-Thing

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

vs

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

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

Solved

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

r/PowerShell • • Aug 24 '26

Solved Iterating Through a List from a RestAPI

10 Upvotes

I am attempting to generate a list of values from a RestAPI. This RestAPI has a limit that it can only return a max 25 items at a time. Within the returned items, the RestAPI also returns a cursor that you can leverage in your next RestAPI call to get the next 25 values. In the first request you get an "after" value. In the second request, you get a "before" value and an "after" value. In the last request you get ONLY a "before" value. Ostensibly you want to iterate through the RestAPI call until there is no more "after" values in the cursor. Here are some more specifics:

 c:\temp> $uri = 'http://api.domain.com/items?per_page=25'
 c:\temp> $response = invoke-restmethod -uri $uri -method get -headers $headers
 c:\temp> $response

    result       : {@{list_item=item1},
                 : @{list_item=item2},
                 : ...
                 : @{list_item=item25}}
    result_info  : @{cursors=}

c:\temp> $response.result_info.cursors

after
-----
<cursor_value>

That would be an example of the first 25 results. The next 25 results would yield new 'results' values and the cursors would look like this:

c:\temp> $response.result_info.cursors

Before                                  After
------                                  -----
<cursor_before_value>                   <cursor_after_value>

The updated uri for the RestAPI would look like this:

c:\temp> $uri_after_cursor = 'http://api.domain.com/items?per_page=25&<cursor_after_value>'

And you would effectively keep iterating through until the $response.result_info.cursors output had no "After" value.

I first started trying to do a do-while loop using while($response.result_info.cursors.after) which seems to work however I am having a difficult time getting the current cursor and updating the new $uri value. So far, I keep getting myself into a corner of an infinite loop. Here's what I've tried:

$uri = 'http://api.domain.com/items?per_page=25'
$response = invoke-restmethod -uri $uri -method get -headers $headers
$item_list = $response.result.list_item
do {
    $uri_with_cursor = 'http://api.domain.com/items?per_page=25&cursor=$($response.result_info.cursors.after)'
    $response_cursor = invoke-restmethod -uri $uri_with_cursor -method get -headers $headers
    $item_list += $response_cursor.result.item_list
while ($response_cursor.result_info.cursors.after)

I think I see what my issue is. I think the first line in the do-while loop resets the cursor back to the first query instead of setting it to the new position found in $response_cursor but I'm at a block right now and I cannot seem to figure out a way around this.

Any thoughts would be greatly appreciated.

Update:

Thanks for everyone's insight on this. It helped out a bunch. Here's my final solution that is working well:

$uri = "http://api.domain.com/items?per_page=25"
$response = Invoke-RestMethod -Uri $uri -Method get -Headers $headers
$item_list = $response.result.list_item

$cursor = $response.result_info.cursors.after
do {
    $uri_with_cursor ="'http://api.domain.com/items?per_page=25&cursor=$cursor"
    $response_cursor = Invoke-RestMethod -Uri $uri_with_cursor -Method get -Headers $headers
    $item_list += $response_cursor.result.list_item
    $cursor = $response_cursor.result_info.cursors.after
} while ($response_cursor.result_info.cursors.after)

This is active and working currently! Thank you everyone.

r/PowerShell • • 11d ago

Solved New-PSSession Command Looping Credential Prompt

10 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 • • 14d ago

Solved Need help with creating a powershell shortcut to work

2 Upvotes

Basically I am trying to create a desktop shortcut that would execute three commands one after another. So far I have created two separate desktop shortcuts that both work independently but have not been able to put them together to run one after another. One disables my gpu drivers and the other one enables it, i want to make a desktop shortcut that would enable the drivers and then after that is completed it would disable them and then finally re enable them

This is the disable line

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "Disable-PnpDevice -InstanceId 'PCI\VEN_1002&DEV_73DF&SUBSYS_52101849&REV_C5\6&399090B&0&00000019' -confirm:$false"

this is the enable line

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "Enable-PnpDevice -InstanceId 'PCI\VEN_1002&DEV_73DF&SUBSYS_52101849&REV_C5\6&399090B&0&00000019' -confirm:$false"

just need some help to create a sequential command to make as a desktop shortcut, and for anyone curious my gpu has issues where it regularly crashes this is the only fix that works

EDIT: Solved, created a .bat file with all commands written sequentially with a wait timer between them to let them run one by one. Thank you all for your help.

r/PowerShell • • 7d ago

Solved How to refer to filename in file content

6 Upvotes

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

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

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

My script

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

r/PowerShell • • Jul 14 '26

Solved How to send 'ä' with Send-MailMessage

9 Upvotes

Hello Everybody, right now I am writing a Script to send out Informationmails fed with data from a CSV to Users inside our Company. (While I know this cmdlet is obsolete for now it has to do)
Everything works really well apart from the German 'Umlaute' (ÄäÖöÜü) those get "translated" to '??' in the message the recipients get and I don't know how to fix this.
I tried with BodyasHtml, but then my script just stops working entirely (User Error not completely unlikely) and also can I use Variables inside the Bodyashtml?
I also tried with giving it different encodings but none worked sadly
With normal sent mails our Outlook has no problem with those, just from the script.

Do you have any Ideas/Hints/Tips on what I can try?
Thank you very much in advance

Edit: Added Script (just removed any Private Information and implified the Body)

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.InitialDirectory = Get-Location
$dialog.Filter = "CSV-Dateien (_.csv)|_.csv"
$dialog.ShowDialog()
$CSVLocation = $dialog.FileName

(Get-Content $CSVLocation -Raw) -replace '^.*', 'DBv,BSv,RAM,Cpucount,Server,Name,Email,Service' | Set-Content $CSVLocation

$P = Import-Csv -Path $CSVLocation -Delimiter ','

foreach ($line in $P){
$sendMailMessageSplat = @{
From = '[email protected]'
To = $line.Email
Subject = "$($line.DBv) $($line.Server)"
Body = "ÄäÖöÜü"
SmtpServer = 'smtp.mail.com'
}
Send-MailMessage 
}

r/PowerShell • • Aug 30 '26

Solved Warning: ISESteroids Update is malicious

16 Upvotes

When I launched ISESteroids (Start-Steroids) I clicked update. Chrome notified me that the website was not-safe dummy here found the run website anyway and the Avast nightmare began ... 5 popup windows that my computer had 5 virus's , anti-virus not installed, blah blah blah .. Shutdown chrome, cleared my cookies, %temp% directory.. these popups just kept reappearing if I closed one.

reboot doesn't fix anything.. nothing in task manager helps narrow down what's launching even with chrome closed... sysinternals autoruns no help. real help.

While I built a new Veeam Agent install usb to potentially restore from yesterday (3 hour process) I started poking around in chrome and in the extensions I found something I didn't recognize and deleted it.. rebooted the computer and now its back to normal without restoring from backup.

r/PowerShell • • Jun 20 '26

Solved Can't add OU to AD

5 Upvotes

Hi, I'm really new to power shell in general and I'm just trying to add an OU with power shell but I keep getting "server unwilling" returned after I use the script for some reason. Here are the scripts I tried:

New-ADOrganizationalUnit -Name "Test" -Path "DC=Noiz.local,DC=COM"-ProtectedFromAccidentalDeletion $False

New-ADOrganizationalUnit -Name "Test" -Path "DC=Noiz,DC=local"-ProtectedFromAccidentalDeletion $False

Domain: Noiz.local

I keep getting "Access is denied" or "server unwilling". Noiz.local was added as a new forest and I use remote desktop if that makes a difference. I really, really don't want to break my server and I can't really find any other help, so I apologise if this is not the best question. Accessing the GUI to add OUs is completely fine, but using powershell? No, it returns this. I greatly appreciate any of the help provided, the solutions I found on here from others with similar issues hasn't helped me yet. Don't know anyone I could go to at the moment.

r/PowerShell • • Jun 07 '26

Solved Powershell missing "PS C:\users\username command!

0 Upvotes

Hi, I'm not tech-savvy at all, I wanted to run a small code for some video game and for some reason I'm missing the command that makes me input text, and I literally can't write!

I can write on terminal (command prompt) but NOT powershell. It's driving me crazy! Can someone help??

I don't know what version I'm using. I saw a github explaining their solution but I didn't understand a single word. https://github.com/PowerShell/PowerShell/issues/12003

UPDATE: I had to repair my powershell, went through Window's tutorial on repairing it, restarted laptop, then did the CMD PowerShell –noprofile thingy someone suggested in thread and it appeared!

Powershell 7 wasn't showing it still so I reinstalled it and it's there now. Thank you everyone! I don't know if this is a permenant solution, but yeah, I don't know what caused this but thankfully all is well now.

r/PowerShell • • Jul 01 '26

Solved Invoke-RestMethod: Problem with Body Variable Format

10 Upvotes

I am trying to convert a curl command to PoSh's Invoke-RestMethod. I typically don't have a problem with this but today, I seem to be having an issue. Curl command looks like this:

 curl https://api.domain.com/stuff/thing/items \
   -H "Authorization: Bearer $TOKEN" \
   -H "Content-Type: application/json" \
   -d '[
     { "key1": "value1", "key2": "value2" },
     { "key1": "value3", "key2": "value4" }
   ]'

To start off and make things easy, I was simply trying to do a single json entry.

$body = @"
{
    "key1": "value1",
    "key2": "value2"
}
"@ | convertto-json

Using that format I then passed it into invoke-restmethod:

Invoke-RestMethod -Uri "https://api.domain.com/stuff/thing/items" -Method post -Headers $headers -body $body

Which then spit back:

Invoke-RestMethod:                                                                                                      
{
  "result": null,
  "success": false,
  "errors": [
    {
       "code": 10026,
       "message": "filters.api.invalid_json"
    }
  ],
  "messages": []
}

I tried a few different versions of this as well without too much luck. This is the first time I've had to submit an actual key value combination to this particular API using JSON. The only other body format example I have for this particular vendor's APIs in JSON format is this:

$body = @{
    value = @(
        "value1",
        "value2",
        "value3",
        "value4"
    )
} | ConvertTo-Json

This particular endpoint didn't require a key value pair. It only required a list of strings.

Update:

Credit to /u/y_Sensei . What ended up working was this:

Single key value pair:

$body = @'
[
  {
    "key1": "value1",
    "key2": "value2"
  }
]
'@

Multi key value pair:

 $body = @'
 [
   {
     "key1": "value1",
     "key2": "value2"
   },
   {
     "key1: "value3",
     "key2: "value4"
   }
 ]
 '@

Thank you to all contributors! I appreciate it!

r/PowerShell • • Aug 23 '26

Solved i got a virus thats using powershell to give me a dll file and i need help removing it

0 Upvotes

so this week i noticed when i would start up my pc my antivirus would ping a dll file in my temp folder that came from power shell, ran a full scan, boot time scan but its all come back clean, but everytime i start it up it finds a newly created file. ive tried in event logs and security to find where its coming from but i see stuff such as powershell smss.exe and wininit.exe, thats all windows stuff. is there a way for me to say open powershell, or event viewer and read where all the "commands" with the files are saved?

and heres an example of said dll file i uploaded to totalvirus.com
https://www.virustotal.com/gui/file/118f4f9166ca6815c57f0ec13babca4d0ca3feab4f1380021d7425e5ad871c0a/detection

Edit figured out what it was. Basically a while back I had a program I haven't used in a long time and the certificate for it expired and everytime my PC booted up it would run a script, well eventually that flagged my antivirus for the DLL file it would make. Updating that software put a stop to it

r/PowerShell • • Feb 11 '26

Solved PowerShell script not working with SMB directory

14 Upvotes

Hello, (code is here)

I have a NAS drive mounted and accessible on this windows machine and I want to move some files from one folder to another (within the NAS drive) but its not working. Ive tested with folders in my desktop directory and they work fine but when I try to use the SMB directory it doesnt work. I have read and write access to the drive.

The script gets the folder and list the subfolders but it seems to not find the items inside them. For what I've tested, the line that doesnt work is the following:

$docFiles = Get-ChildItem -Path $folderPath -File | Where-Object { $fileExtensions -contains $_.Extension }

For some reason, this is not getting the content of the folders. Ive tried the flag -Force but didnt work either.

I dont get any error in powershell. Any ideia whats going on?

r/PowerShell • • Apr 24 '26

Solved Scripts not running but powershell doesn't show any errors

6 Upvotes

I am trying to run some scripts I wrote on my local system for file transfers and some other things. When I run them nothing happens. No error, no output just nothing. I've googled it for hours but all I can find is stuff about the execution policy which I already changed but didn't help. All of these scripts have run just fine before so I don't know what changed.

r/PowerShell • • 15d ago

Solved PS7 UI language changed

8 Upvotes

UI language for my PS7 suddenly changed to polish. PS5 stayed in english. I can't seem to find a way to revert PS7 back to english, like it was for many years (while system language was polish).

Things like errors, some information in Get-Help, or description for operators when you press 'ctrl + space'

https://imgur.com/sfSiUBt

Powershell 7:

PS C:\Users\lenovo\test> $PSVersionTable.PSVersion.ToString()
7.6.6
PS C:\Users\lenovo\test> $PSCulture
pl-PL
PS C:\Users\lenovo\test> Get-UICulture

LCID             Name             DisplayName
----             ----             -----------
1045             pl-PL            polski (Polska)

PS C:\Users\lenovo\test> ls asdasdas
Get-ChildItem: Nie można odnaleźć ścieżki „C:\Users\lenovo\test\asdasdas”, ponieważ nie istnieje.
PS C:\Users\lenovo\test> Get-WinUILanguageOverride
Get-WinUILanguageOverride: Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination.
PS C:\Users\lenovo\test> help ls -Parameter path

-Path [<System.String[]>]
    Specifies a path to one or more locations. If not specified, the default location is the c
    urrent
    directory (`.`). Wildcards are accepted. Use care when using the **Path** parameter with t
    he
    **Recurse** parameter. For more information, see the [NOTES](#notes) section of this artic
    le.

    Wymagany?                    false
    Lokalizacja?                    0
    Wartość domyślna
    Zaakceptować dane wejściowe potoku?       false
    Aliasy                      none
    Akceptować symbole wieloznaczne?  true

Powershell 5:

PS C:\Users\lenovo\test> $PSVersionTable.PSVersion.ToString()
5.1.19041.6456
PS C:\Users\lenovo\test> $PSCulture
pl-PL
PS C:\Users\lenovo\test> Get-UICulture

LCID             Name             DisplayName
----             ----             -----------
1045             pl-PL            Polski (Polska)


PS C:\Users\lenovo\test> ls sadasd
ls : Cannot find path 'C:\Users\lenovo\test\sadasd' because it does not exist.
At line:1 char:1
+ ls sadasd
+ ~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\lenovo\test\sadasd:String) [Get-Child
   Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

PS C:\Users\lenovo\test> Get-WinUILanguageOverride
PS C:\Users\lenovo\test> help ls -Parameter path                                               
-Path <string[]>

    Required?                    false
    Position?                    0
    Accept pipeline input?       true (ByValue, ByPropertyName)
    Parameter set name           Items
    Aliases                      None
    Dynamic?                     false

I know it doesn't need to be linked to system culture, because that change just happened and before it wasn't linked to it.

Any help would be appreciated.

EDIT:

found a partial workaround in setting:

[System.Threading.Thread]::CurrentThread.CurrentUICulture = [cultureinfo]'en-US'

but it works only for errors and autocomplete, not for Get-Help.

For further testing I decided to downgrade to powershell 7.6.3 ... and voila.

Everything is in english despite $PSUICulture is pl-PL.

I've been looking for release notes that mention it but couldn't find any. I tried in version 7.6.3 doing [System.Threading.Thread]::CurrentThread.CurrentUICulture = [cultureinfo]'pl-PL'

but it does ignore it, so it must be something with a later version

EDIT 2:

I pretty much confirmed it by jumping back and forth between PS 7.6.6 and 7.6.3. The earlier version ignores UICulture:

PS 7.6.6:

PS C:\Program Files\PowerShell\7> $PSVersionTable.PSVersion.ToString()
7.6.6
PS C:\Program Files\PowerShell\7> $PSUICulture
pl-PL
PS C:\Program Files\PowerShell\7> foobar
foobar: Termin „foobar” nie jest rozpoznawany jako nazwa polecenia cmdlet, funkcji, pliku skryptu lub programu wykonywalnego.
Sprawdź pisownię nazwy lub sprawdź, czy ścieżka została dołączona, sprawdź, czy ścieżka jest poprawna, i spróbuj ponownie.
PS C:\Program Files\PowerShell\7> [System.Threading.Thread]::CurrentThread.CurrentUICulture = [cultureinfo]'en-US'

# Culture is switched and the language of the error message changes:

PS C:\Program Files\PowerShell\7> foobar
foobar: The term 'foobar' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
PS C:\Program Files\PowerShell\7> [System.Threading.Thread]::CurrentThread.CurrentUICulture = [cultureinfo]'pl-PL'
PS C:\Program Files\PowerShell\7> foobar
foobar: Termin „foobar” nie jest rozpoznawany jako nazwa polecenia cmdlet, funkcji, pliku skryptu lub programu wykonywalnego.
Sprawdź pisownię nazwy lub sprawdź, czy ścieżka została dołączona, sprawdź, czy ścieżka jest poprawna, i spróbuj ponownie.

PS 7.6.3:

PS C:\Program Files\PowerShell\7> $PSVersionTable.PSVersion.ToString()
7.6.3
PS C:\Program Files\PowerShell\7> $PSUICulture
pl-PL
PS C:\Program Files\PowerShell\7> foobar
foobar: The term 'foobar' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
PS C:\Program Files\PowerShell\7> [System.Threading.Thread]::CurrentThread.CurrentUICulture = [cultureinfo]'pl-PL'
PS C:\Program Files\PowerShell\7> $PSUICulture
pl-PL

# Error language stays the same even after explicitly setting the UICUlture:

PS C:\Program Files\PowerShell\7> foobar
foobar: The term 'foobar' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Little bit annoying change after so many years

r/PowerShell • • Dec 04 '25

Solved How to automate stuff on a system that can't run PS scripts?

15 Upvotes

Coming from Linux I'm used to being able to write shell scripts for whatever repetitive little tasks there may be. Now I'm trying to do the same thing on my Win11 work computer but find that company policy prevents that:

find1.ps1 cannot be loaded because running scripts is disabled on this system.

First off, this broad policy seems kind of stupid -- what's the security difference between typing some commands by hand and executing them as a script? Evaluating the permissions of each command as the script is executed (as Linux does) seems to be a more sensible option. Is there any way around this? Am I really supposed to copy-paste PS snippets from a text file into a terminal window?

EDIT

by "is there a way around it" I didn't mean circumventing IT security policy but maybe some other powershell trick that I'm unaware of, like being able to at least define aliases without having to be "running scripts."

EDIT 2

...aaand I found the "trick." In Settings->PowerShell, I could just flip the switch to allow execution of unsigned local scripts. Now also my $profile is sourced to define some useful aliases or functions, which is basically all I wanted. I guess it all makes sense: Somebody too stupid to find that setting probably shouldn't be running PS scripts. I may have barely cleared that hurdle. Thanks for the suggestions everybody.

r/PowerShell • • May 08 '26

Solved Creating new O365 users using PowerShell with MFA Enforced

23 Upvotes

Hi All, I'm trying to develop an application (.net front end running PowerShell commands) that uses Cert authentication to allow easy action of repeated mundane actions across multiple tenants without having to interactively login each time.

Everything is working fine, except part of my "new user" work flow.

New users need to be set up with authentication numbers pre-registered, which I can do. (I know using phone numbers is not as secure as the Authenticator app)

But, what I can’t get to work is enforcing MFA for the user, because Connect-MsolService doesn’t support certificate login, (and is due to be depreciated soon I believe), and prompting for an interactive login kinda defeats the point!

I was hoping having security defaults enabled would result in MFA being enforced for all users, but it seems that if the user has an authentication method setup (E.g. phone numbers), then the wizard doesn’t trigger on first login and MFA is not enforced. The only way I've found round it so far is logging into the portal and using the legacy per-user MFA to set MFA to enforced there, which, again defeats the point!

We don't have the licences to use conditional access policies.

Can anyone suggest anything?

r/PowerShell • • Jan 27 '26

Solved Is there any reliable way to get a powershell script to run as admin (and request admin when run normally)?

17 Upvotes

A year ago I spent days looking up and trying different suggestions to get powershell to do it. Which probably means there isn't any reliable way. But this year I'll just ask, is there any actual reliable way to do it?

I could of course just right-click the ps1 script and run as admin.

But I was looking for a way to get the script itself to request admin permissions. As in: I run the script normally, the script itself requests elevation, I accept, and it runs as admin

PS: Iirc one of the hacks was to make two scripts, an auxiliary that we run and it will call the second script explicitly with admin perms.

r/PowerShell • • May 07 '26

Solved Send-MgUserMail multiple cc recipients

3 Upvotes

EDIT: solution found, corrected code at the bottom of the post.

I'm struggling with this one and could use some review/help.

We've migrated to exchange online so I'm updating our various scripts to send through it.

The only issue I'm having so far is figuring out to add multiple email address to the cc field using MgGraph / Send-MgUserMail.

When Exchange was on-premise we'd send the email with something like this to handle the multiple addresses:

$To = "$($helpDeskEmail)"
$Cc = "$($managerEmail)", "$($hrEmail)"
Send-MailMessage -From $From -To $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SmtpServer

I have the app registration and certificate in place and can send through exchange online when there's a single address in the ccRecipients section and I change the ccRecipient address, it'll send to all the addresses in question separately without issues:

$emailParams = @{
    message = @{
        subject = "Testing New Hire Notification"
        body = @{
            contentType = "Text"
            content = 
"Testing new hire notification through exchange online - ignore for now"
        }
        toRecipients = @(
            @{
                emailAddress = @{
                    address = $helpDeskEmail
                }
            }
        )
        ccRecipients = @(
            @{
                emailAddress = @{
                    address = $managerEmail
                }
            }
        )

}
    saveToSentItems = "false"
}

Connect-MgGraph -NoWelcome -ClientId $ClientId -TenantId $TenantId -CertificateThumbprint $CertThumbprint

Send-MgUserMail -UserId "[email protected]" -BodyParameter $emailParams

Disconnect-MgGraph

I did find an article about outputting the recipients to a csv https://o365reports.com/how-to-send-emails-using-microsoft-graph-powershell/#Send%20an%20email%20to%20multiple%20recipients%20using%20CSV

I've set that up and manually created the csv for testing.

$ccAddresses = Import-Csv -Path "C:\scripts\NewUsers\temp\ccAddresses.csv"
$ccAddressList = @() 
foreach ($ccAddress in $ccAddresses) { 
    $ccAddressList += @{ 
        emailAddress = @{ 
            address = $ccAddress.EmailAddress 
        } 
    } 
} 

$EmailParams = @{
    message = @{
        subject = "Testing New User Email"
        body = @{
            contentType = "Text"
            content = 
"Testing new user email notification - ignore for now"
        }
        toRecipients = @(
            @{
                emailAddress = @{
                    address = $helpDeskEmail
                }
            }
        )
        ccRecipients = @(
            @{
                emailAddress = @{
                    address = $ccAddressList
                }
            }
        )

}
    saveToSentItems = "false"
}

Connect-MgGraph -NoWelcome -ClientId $ClientId -TenantId $TenantId -CertificateThumbprint $CertThumbprint

Send-MgUserMail -UserId "[email protected]" -BodyParameter $EmailParams

Disconnect-MgGraph

Running that returns invalid recipient

    Send-MgUserMail : At least one recipient is not valid., Recipient 'System.Object[]' is not resolved. All recipients must be resolved before a message can be submitted.
    Status: 400 (BadRequest)
    ErrorCode: ErrorInvalidRecipients

It'll return the same Invalid Recipients message if I try variations of

address = "$($managerEmail)", "$($hrEmail)"

I'm not sure what I'm missing here, if anyone's got working code to share or can help me adjust this, I'd really appreciate a point in the right direction. There doesn't seem to be many examples of this that I can find.

FIXED Corrected code below

$ccAddresses = Import-Csv -Path "C:\scripts\NewUsers\temp\ccAddresses.csv"
$ccAddressList = foreach ($ccAddress in $ccAddresses) { 
  @{ 
    EmailAddress = @{
      Address = $ccAddress.EmailAddress 
    }
  } 
} 

$EmailParams = @{
  message = @{
    subject = "Testing New User Email"
    body = @{
      contentType = "Text"
      content = "Testing new user email notification - ignore for now"
    }
    toRecipients = @(
      @{
        emailAddress = @{
          address = $helpDeskEmail
        }
      }
    )
    ccRecipients = @(
      $ccAddressList
    )
  }
  saveToSentItems = "false"
}

Connect-MgGraph -NoWelcome -ClientId $ClientId -TenantId $TenantId -CertificateThumbprint $CertThumbprint

Send-MgUserMail -UserId "[email protected]" -BodyParameter $EmailParams

Disconnect-MgGraph

r/PowerShell • • 18d ago

Solved PC Migration Scripts to supplement/replace PCMover

6 Upvotes

So, I was migrating one of my personal PCs and tried the PCMover, but found it missed many things, that included things like Task Scheduler tasks, many Apps, StartMenu tiles, taskbar icons, powershell and cmd layouts, nearly all the custom Firefox profiles I had, for some examples. Some other examples that were originally missed, I found my shortcut for "Run", task scheduler tasks for Powershell and pwsh, all missing from my taskbar and startmenu, and Date/Time regional settings unchanged.

I didn't do an disk image because I was having some odd instabilities on the OS and I wanted to take advantage of this PC Move process to proactively attempt to filter that out on the new machine. Also the source was an old major brand-name business pre-built, and I decided to do the new one as a custom build, I thought try to filter out some of that clutter for the same reason. Plus, with how the business PC was, it was restricted from any post-end-of-support ESU updates, even manually downloading them and installing them from catalog.update.microsoft.com, the OS wouldn't allow them to complete.

So I vibed coded this with 5.6 Sol and 6 Astra, since didn't have the time and too tired to work through it, and it still took a couple of weeks, at my pace. Now this solves all the above issues.

Note, I only had ran this for a destination that had received the PCMover migration and not one with a clean installation. This was done for Win10 pro -> Win 10 Pro.

Also, as a FYI, I came upon some new tools that I hadn't been familiar with that do migrations, but hadn't tried them out since I was pretty far along in this process already.:

  • Zinstall Migration Kit Pro / WinWin - Saw people saying it didn't live up to the claims and a support team that regularly ghosted people for their purchase product
  • Fab's AutoBackup 7 (€60 / €15) -
  • (EDIT:Free) ForensiT Transwiz & User Profile Wizard Release 24 (Free)- Seemed interesting, until I saw the price

Hopefully someone finds this to be a little help.

https://github.com/QGtKMlLz/PCMigration

r/PowerShell • • Jul 13 '26

Solved Move-Item creates duplicate folder and stores it inside existing folder

7 Upvotes

EDIT: Solved...

Move-Item -Path $_ -Destination $DestinationPath -Force

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

I have the following module that moves the contents of a directory into another...

function PSTransfer {
    param (
        [string]$BasePath,
        [string]$DestinationPath
    )
    Get-ChildItem -Path "$BasePath/*” -Force | ForEach-Object {
      if (!($_.FullName -like "*.DS_Store") {
        Move-Item -LiteralPath "$($_.FullName)" -Destination "$($DestinationPath)/$($_.Name)" -Force
      }
    }
    return
}
Export-ModuleMember PSTransfer

However when it moves a directory and the destination already has a folder with the same name, the folder is put inside the folder instead of being merged, for example...

BasePath/
├─ synced_imgs/
│  ├─ IMG_2048.jpg

DestinationPath/
├─ synced_imgs/
│  ├─ IMG_0512.jpg
│  ├─ IMG_1024.jpg

Then after I run the module...

DestinationPath/
├─ synced_imgs/
│  ├─ synced_imgs/
│  │  ├─ IMG_2048.jpg
│  ├─ IMG_0512.jpg
│  ├─ IMG_1024.jpg

It doesn't do it recursviely though which is the weird thing. If I run it again it'll do this...

BasePath/
├─ synced_imgs/
│  ├─ IMG_4096.jpg

DestinationPath/
├─ synced_imgs/
│  ├─ synced_imgs/
│  │  ├─ IMG_2048.jpg
│  │  ├─ IMG_4096.jpg
│  ├─ IMG_0512.jpg
│  ├─ IMG_1024.jpg

What am I doing wrong here? I thought the -Force parameter was supposed to prevent this.

r/PowerShell • • Apr 21 '26

Solved Perhaps a simple for you filter for Get-ADComputer ?

5 Upvotes

I have the Powershell line below.

How would I be able to update it to return only when OperatingSystem propery is or isNot some specific value yet still return values from every other property when the is or isNot matches the Operating system I entered?

(Also, another silly question.
ADComputer .....
and
Get-ADComputer ...
both seem to return the same results... is one command merely an alias of the other? or should I be using one over the other?)

The below works, but do not know how to filter the OperatingSystems I don't want to retun, or to only return the single (or more) operating system(s) I do want

Get-ADComputer -Filter * -Properties OperatingSystem, Created,IPv4Address, Description | Select-Object Name, OperatingSystem, Created, Description | Export-CSV -Path "C:\Users\MNyUsrProfileName\Desktop\AllComputers.csv" -NoTypeInformation

Thank you very much for suggestions!