Questions tagged [powershell]

PowerShell is a cross-platform command line and scripting utility from Microsoft. Use this tag for questions about writing and executing PowerShell scripts ONLY. Programming questions specific to the cross-platform version PowerShell Core (Windows, macOS, and Linux) should be tagged [powershell-core]. Questions about system administration should be asked on Super User or Server Fault.

Questions about Windows administration tasks involving PowerShell should be asked on Super User or Server Fault. On-topic questions are for writing scripts ONLY

Windows PowerShell

is an interactive shell and scripting language originally included with Microsoft Windows 7 and Microsoft Windows Server 2008 R2 and above. It includes a command-line shell (Windows PowerShell) for interactive use, an underlying scripting environment to run scripts away from the command-line and a GUI script editing / debugging environment (Windows PowerShell ISE). See: Getting Started with Windows PowerShell.

As a language, has syntax for literal arrays and hashtables, support for regexes, pattern matching, and string expansion. It's built on the .NET framework so it has Unicode support, can be locale/culture aware, and can access .NET framework methods directly.

As a command-line shell, it is designed around cmdlets named in the form {Verb}-{Noun}, intending that the same kinds of commands work across many domains. E.g. Get-Date returns the current date, and Get-Process returns an array of objects representing running processes which can be piped to other commands that work with process objects. Many commands and keywords have short aliases to reduce typing.

As a system management environment, Windows components and Microsoft products have been extended to provide native PowerShell interfaces as part of creating a unified managing system for Windows systems, including:

Third-party vendors also offer PowerShell integration, including:

takes the Unix idea of piping text between programs and manipulating text, and enhances it by piping .NET object instances around. Because objects carry type information (e.g. dates and times), and complex state (e.g. properties and methods, hashtables, parsed XML data, and live network sockets) this makes many tasks easy that would be difficult or impractical to do by passing text between programs.

Along with interacting with the PowerShell console or the PowerShell ISE, there are also several third-party IDE options including Sapien's PrimalScript ISE.

Example Usage

# List all processes using > 100 MB of PagedMemory in descending sort order (v3_
C:\PS> Get-Process | Where PagedMemorySize -GT 100MB | Sort -Descending

# PowerShell can handle numbers and arithmetic
C:\PS> (98.6 - 32) * 5/9
37

# Production orientation allows experimentation and confirmation
C:\PS> Get-ChildItem C:\Users\John *.bak -r |
           Where {$_.LastWriteTime -gt (Get-Date).AddDays(-7)} |
           Remove-Item -WhatIf
What if: Performing operation "Remove File" on Target "C:\Users\John\foo.bak"

C:\PS> Get-Process iexp* | Stop-Process -Confirm

Confirm
Are you sure you want to perform this action?
Performing operation "Stop-Process" on Target "iexplore (7116)".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is Y):

Common Gotchas

Executing EXE files via a path with spaces requires quoting the path and the use of the call operator - &

C:\PS> & 'C:\Program Files\Windows NT\Accessories\wordpad.exe'

Calling PowerShell functions does not require parenthesis or comma separated arguments. PowerShell functions should be called just like a cmdlet. The following examples demonstrates the problem caused by this issue e.g.:

C:\PS> function Greet($fname, $lname) {"My name is '$lname', '$fname' '$lname'"}
C:\PS> Greet('James','Bond') # Wrong way to invoke this function!!
My name is '', 'James Bond' ''

Note that both 'James' and 'Bond' are packaged up as a single argument (an array) that is passed to the first parameter. The correct invocation is:

C:\PS> Greet James Bond
My name is 'Bond', 'James' 'Bond'

Note that in PowerShell 2.0, the use of Set-StrictMode -version 2.0 will catch this type of problem.

PowerShell Profiles

Another common issue when moving files from a user machine into a production environment is the profile setting discrepancy. A user's machine might have a profile.ps1 defined inside this folder

%UserProfile%\Documents\WindowsPowerShell

The profile file is used to define certain commands are automatically executed prior to running a script. Common commands might include adding a PowerShell snap-in. To minimize this type of confusion between environments, it is recommended to run tests with the PowerShell command line via the -NoProfile flag. This will ensure the profile script is not executed.

More information on profiles can be found here.

Extensible functionalities

One of the great features of PowerShell is its extensibility: we can add functionality by importing modules which are a package of cmdlets, functions, and aliases specialized on a particular domain (such as database administration, virtual machine administration, etc.).

Here are the most commonly used modules by the community:

  • PSReadLine PSReadLine replaces the command line editing experience in PowerShell.exe "PSReadLine replaces the command line editing experience in PowerShell.exe for versions 3 and up." Included in Windows 10.

  • Powertab "PowerTab offers enhanced tab expansion for PowerShell."

  • PSCX "PowerShell Community Extensions (PSCX) is aimed at providing a widely useful set of additional cmdlets, providers, aliases, filters, functions, and scripts for Windows PowerShell that members of the community have expressed interest in but haven't been added to PowerShell yet."

PowerShell Core

Since 2016, an open-source and cross-platform (Windows, macOS, and Linux) version of PowerShell has been in alpha and then beta state. Achieving general availability in 2018, PowerShell Core is built on the .NET Core Framework. Questions about functionality specific to PowerShell Core should be tagged .

Resources

114499 questions
22
votes
4 answers

PowerShell Split a String On First Occurrence of Substring/Character

I have a string that I want to split up in 2 pieces. The first piece is before the comma (,) and the second piece is all stuff after the comma (including the commas). I already managed to retrieve the first piece before the comma in the variable…
DarkLite1
  • 13,637
  • 40
  • 117
  • 214
22
votes
2 answers

Powershell profile "on exit" event?

I'm looking for a way to automatically do some clean up tasks when the PowerShell session quits. So for example in my profile file I start a process which needs to run in the background for quite a lot of tasks and I would like to automatically…
poke
  • 369,085
  • 72
  • 557
  • 602
22
votes
3 answers

PowerShell Invoke-Sqlcmd switches into sqlps session

I am writing a script in PowerShell ISE and I am using Invoke-Sqlcmd. After the command is executed the Powershell session switches into sqlps session (PS SQLSERVER:>) and I can't execute script for the second time. I have to quit PowerShell ISE and…
scar80
  • 1,642
  • 2
  • 18
  • 36
22
votes
1 answer

Update Variable in TeamCity powershell script

I am trying to update an enviroment variable in TeamCity using Powershell script. However, it does not update the value of the variable. How can I do this? Below is my current code which gets the currentBuildNumber fine: $currentBuildNumber =…
Jake Rote
  • 2,177
  • 3
  • 16
  • 41
22
votes
2 answers

PowerShell Round & Format Float to max 2 decimals?

I found lots of stuff to format floats to common known numbers, but how can I format a float to a max of 2 decimals, but only if the decimals are needed? Examples: 1.11 # not 1.111 1.12 # it was 1.116 (round up) 1.1 # not 1.10 1 # not…
gooly
  • 1,241
  • 7
  • 20
  • 38
22
votes
3 answers

how to recreate a working CURL command with Invoke-WebRequest in Powershell

This curl command works as desired: curl -H "X-Api-Key:j65k423lj4k2l3fds" ` -X PUT ` -d "alerts_enabled=true" ` https://some/working/file.xml How can I recreate this natively in PS with Invoke-WebRequest? I've…
user3561945
  • 441
  • 1
  • 3
  • 9
22
votes
2 answers

Are 'Scheduled Job" and "Scheduled Task" the same thing in Powershell context?

I am trying to create a scheduled task from Powershell. I was readin the document for cmdlet: New-ScheduledJobOption. And I am a bit confused... Question: Are 'Scheduled Job" and "Scheduled Task" the same thing in Powershell context? Or there is a…
pencilCake
  • 51,323
  • 85
  • 226
  • 363
22
votes
6 answers

PowerShell: How to limit string to N characters?

substring complains when I try to limit a string to 10 characters which is not 10 or more characters in length. I know I can test the length but I would like to know if there is a single cmdlet which will do what I need. PS C:\>…
Ethan Post
  • 3,020
  • 3
  • 27
  • 27
22
votes
3 answers

Encode a string in UTF-8

I want to encode a string into UTF8 in PowerShell. This is what I tried: $consumer_key ="xvz1evFS4wEEPTGEFPHBog" $enc_consumer_key = System.Text.UTF8Encoding($consumer_key) But I get an error: System.Text.UTF8Encoding in not recognize as the name…
user3562182
  • 365
  • 1
  • 5
  • 8
22
votes
4 answers

How to send multipart/form-data with PowerShell Invoke-RestMethod

I'm trying to send a file via Invoke-RestMethod in a similar context as curl with the -F switch. Curl Example curl -F FileName=@"/path-to-file.name" "https://uri-to-post" In powershell, I've tried something like this: $uri =…
Jeff
  • 905
  • 2
  • 8
  • 17
22
votes
5 answers

Change audio level from powershell?

How can I use powershell to set the speaker volume? Ive dug around on here and elsewhere online can cant really find an answer. I think I will have to write something in C# that wraps a Win32 API and THEN call it from my powershell script. The…
bitshift
  • 6,026
  • 11
  • 44
  • 108
22
votes
2 answers

Can not convert String to Secure String for use in New-ADUser

I'm using Primal Forms Community Edition to create a GUI that will stream line our new student creation process for our secretaries. In the lower level schools the students use their birthdays as their passwords so they're easy to remember. I have…
ParadoxCTRL
  • 337
  • 2
  • 4
  • 10
22
votes
10 answers

powershell - Remove all variables

I want to remove all user-created variables at the start of a script. Currently I am doing Remove-Variable -Name * but it tries to delete all system variables as well, resulting in lot of error messages. Any other way?
Ammar
  • 485
  • 1
  • 5
  • 14
22
votes
6 answers

Using Get-childitem to get a list of files modified in the last 3 days

Code as it is at the moment get-childitem c:\pstbak\*.* -include *.pst | Where-Object { $_.LastWriteTime -lt (get-date).AddDays(-3)} | Essentially what I am trying to do is get a list of all PST files in the folder above based on them being newer…
Trinitrotoluene
  • 1,388
  • 5
  • 20
  • 39
22
votes
2 answers

Powershell script not recognizing my function

I have a powershell script that parses a file and send an email if it detects a certain pattern. I have the email code setup inside a function, and it all works fine when I run it from the ISE, but I used PS2EXE to be able to run the script as a…
laitha0
  • 4,148
  • 11
  • 33
  • 49