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
173
votes
1 answer

What does the & symbol in powershell mean?

$tool = 'C:\Program Files\gs\gs9.07\bin\gswin64c.exe' & $tool -q -dNOPAUSE -sDEVICE=tiffg4 $param -r300 $pdf.FullName -c quit Can someone explain to me how the this works? What exactly does the & symbol do/mean in powershell?
Peter3
  • 2,549
  • 4
  • 20
  • 40
172
votes
11 answers

How to load assemblies in PowerShell?

The following PowerShell code #Get a server object which corresponds to the default instance $srv = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Server ... rest of the script ... Gives the following error message: New-Object : Cannot…
Baxter
  • 3,035
  • 3
  • 20
  • 15
170
votes
5 answers

What's the better (cleaner) way to ignore output in PowerShell?

Let's say you have a method or a cmdlet that returns something, but you don't want to use it and you don't want to output it. I found these two ways: Add-Item > $null [void]Add-Item Add-Item | Out-Null What do you use? Which is the better/cleaner…
Hinek
  • 9,519
  • 12
  • 52
  • 74
169
votes
4 answers

Why does 'continue' behave like 'break' in a Foreach-Object?

If I do the following in a PowerShell script: $range = 1..100 ForEach ($_ in $range) { if ($_ % 7 -ne 0 ) { continue; } Write-Host "$($_) is a multiple of 7" } I get the expected output of: 7 is a multiple of 7 14 is a multiple of 7 21 is a…
Justin Dearing
  • 14,270
  • 22
  • 88
  • 161
168
votes
2 answers

How to write to the console in PowerShell?

I am having a little confusion about the various ways to print (echo) to the console. I have seen that there are multiple ways to write output to the console, such as: Write-Host "Hello world1" "Hello World2" Out-Host -InputObject "Hello…
Andre
  • 3,717
  • 4
  • 25
  • 29
166
votes
6 answers

PowerShell difference between Write-Host and Write-Output?

What is the difference between Write-Host and Write-Output in PowerShell? Like... Write-Host "Hello World"; Write-Output "Hello World";
daniyalahmad
  • 3,513
  • 8
  • 29
  • 52
164
votes
7 answers

How to do what head, tail, more, less, sed do in Powershell?

On windows, using Powershell, what are the equivalent commands to linux's head, tail, more, less and sed?
Yue Zhang
  • 1,829
  • 2
  • 12
  • 9
164
votes
10 answers

How do I use Join-Path to combine more than two strings into a file path?

If I want to combine two strings into a file path, I use Join-Path like this: $path = Join-Path C: "Program Files" Write-Host $path That prints "C:\Program Files". If I want to do this for more than two strings though: $path = Join-Path C: "Program…
Michael A
  • 4,391
  • 8
  • 34
  • 61
162
votes
12 answers

Using PowerShell credentials without being prompted for a password

I'd like to restart a remote computer that belongs to a domain. I have an administrator account but I don't know how to use it from powershell. I know that there is a Restart-Computer cmdlet and that I can pass credential but if my domain is for…
all eyez on me
  • 1,623
  • 2
  • 11
  • 5
159
votes
11 answers

Capturing standard out and error with Start-Process

Is there a bug in PowerShell's Start-Process command when accessing the StandardError and StandardOutput properties? If I run the following I get no output: $process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru…
jzbruno
  • 1,698
  • 2
  • 12
  • 7
159
votes
6 answers

PowerShell: Store Entire Text File Contents in Variable

I'd like to use PowerShell to store the entire contents of a text file (including the trailing blank line that may or may not exist) in a variable. I'd also like to know the total number of lines in the text file. What's the most efficient way to do…
Nick
  • 8,049
  • 18
  • 63
  • 107
158
votes
6 answers

Executing an EXE file using a PowerShell script

I'm trying to execute an EXE file using a PowerShell script. If I use the command line it works without a problem (first I supply the name of the executable and series of parameters to invoke it): "C:\Program Files\Automated QA\TestExecute…
Eden
  • 3,696
  • 2
  • 24
  • 24
157
votes
14 answers

Removing path and extension from filename in PowerShell

I have a series of strings which are full paths to files. I'd like to save just the filename, without the file extension and the leading path. So from this: c:\temp\myfile.txt to myfile I'm not actually iterating through a directory, in which…
larryq
  • 15,713
  • 38
  • 121
  • 190
157
votes
15 answers

Equivalent of 'more' or 'less' command in Powershell?

Is there a way to paginate output by piping it to a more or less command, similar to those that are available in Linux\Unix shells?
Valentin V
  • 24,971
  • 33
  • 103
  • 152
157
votes
14 answers

Null coalescing in powershell

Is there a null coalescing operator in powershell? I'd like to be able to do these c# commands in powershell: var s = myval ?? "new value"; var x = myval == null ? "" : otherval;
Micah
  • 111,873
  • 86
  • 233
  • 325