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
2829
votes
23 answers

Determine installed PowerShell version

How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?
Tangiest
  • 43,737
  • 24
  • 82
  • 113
2773
votes
50 answers

PowerShell says "execution of scripts is disabled on this system."

I am trying to run a cmd file that calls a PowerShell script from cmd.exe, but I am getting this error: Management_Install.ps1 cannot be loaded because the execution of scripts is disabled on this system. I ran this command: Set-ExecutionPolicy…
Conor
  • 27,759
  • 3
  • 15
  • 4
1075
votes
10 answers

How do you comment out code in PowerShell?

How do you comment out code in PowerShell (1.0 or 2.0)?
labyrinth
  • 13,397
  • 7
  • 35
  • 44
961
votes
17 answers

How to run a PowerShell script

How do I run a PowerShell script? I have a script named myscript.ps1 I have all the necessary frameworks installed I set that execution policy thing I have followed the instructions on this MSDN help page and am trying to run it like…
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
939
votes
24 answers

Setting Windows PowerShell environment variables

I have found out that setting the PATH environment variable affects only the old command prompt. PowerShell seems to have different environment settings. How do I change the environment variables for PowerShell (v1)? Note: I want to make my changes…
Vasil
  • 36,468
  • 26
  • 90
  • 114
912
votes
22 answers

How do I concatenate strings and variables in PowerShell?

Suppose I have the following snippet: $assoc = New-Object PSObject -Property @{ Id = 42 Name = "Slim Shady" Owner = "Eminem" } Write-Host $assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner I'd expect this snippet to show: 42…
Ninja Cowgirl
  • 10,421
  • 8
  • 33
  • 41
686
votes
14 answers

What's the best way to determine the location of the current PowerShell script?

Whenever I need to reference a common module or script, I like to use paths relative to the current script file. That way, my script can always find other scripts in the library. So, what is the best, standard way of determining the directory of the…
Aaron Jensen
  • 25,861
  • 15
  • 82
  • 91
633
votes
15 answers

How to enter a multi-line command

Is it possible to split a PowerShell command line over multiple lines? In Visual Basic I can use the underscore (_) to continue the command in the next line.
eXXL
  • 6,548
  • 3
  • 19
  • 7
603
votes
1 answer

How to handle command-line arguments in PowerShell

What is the "best" way to handle command-line arguments? It seems like there are several answers on what the "best" way is and as a result I am stuck on how to handle something as simple as: script.ps1 /n name /d domain AND script.ps1 /d domain /n…
Aaron Wurthmann
  • 6,367
  • 5
  • 21
  • 14
593
votes
15 answers

How can I check if a string is null or empty in PowerShell?

Is there a built-in IsNullOrEmpty-like function in order to check if a string is null or empty, in PowerShell? I could not find it so far and if there is a built-in way, I do not want to write a function for this.
pencilCake
  • 51,323
  • 85
  • 226
  • 363
576
votes
8 answers

How can I pass an argument to a PowerShell script?

There's a PowerShell script named itunesForward.ps1 that makes iTunes fast forward 30 seconds: $iTunes = New-Object -ComObject iTunes.Application if ($iTunes.playerstate -eq 1) { $iTunes.PlayerPosition = $iTunes.PlayerPosition + 30 } It is…
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
565
votes
15 answers

How do I pass multiple parameters into a function in PowerShell?

If I have a function which accepts more than one string parameter, the first parameter seems to get all the data assigned to it, and remaining parameters are passed in as empty. A quick test script: Function Test([string]$arg1, [string]$arg2) { …
Nasir
  • 10,935
  • 8
  • 31
  • 39
537
votes
11 answers

Terminating a script in PowerShell

I've been looking for a way to terminate a PowerShell (PS1) script when an unrecoverable error occurs within a function. For example: function foo() { # Do stuff that causes an error $host.Exit() } Of course there's no such thing as…
kprobst
  • 16,165
  • 5
  • 32
  • 53
514
votes
17 answers

Equivalent of *Nix 'which' command in PowerShell?

How do I ask PowerShell where something is? For instance, "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths.
DevelopingChris
  • 39,797
  • 30
  • 87
  • 118
511
votes
13 answers

Create directory if it does not exist

I am writing a PowerShell script to create several directories if they do not exist. The filesystem looks similar to…
ecollis6
  • 5,357
  • 4
  • 17
  • 12
1
2 3
99 100