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
297
votes
7 answers

What does $_ mean in PowerShell?

I've seen the following a lot in PowerShell, but what does it do exactly? $_
Micah
  • 111,873
  • 86
  • 233
  • 325
296
votes
14 answers

Can I get "&&" or "-and" to work in PowerShell?

Note: This question originally asked in 2009, when powershell did not have support for the && operator. In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7. https://stackoverflow.com/a/564092/234 Original Question && is…
Orion Edwards
  • 121,657
  • 64
  • 239
  • 328
288
votes
24 answers

How to create a zip archive with PowerShell?

Is it possible to create a zip archive using PowerShell?
Valentin V
  • 24,971
  • 33
  • 103
  • 152
273
votes
11 answers

How do I capture the output into a variable from an external process in PowerShell?

I'd like to run an external process and capture it's command output to a variable in PowerShell. I'm currently using this: $params = "/verify $pc /domain:hosp.uhhg.org" start-process "netdom.exe" $params -WindowStyle Hidden -Wait I've confirmed…
Adam Bertram
  • 3,858
  • 4
  • 22
  • 28
273
votes
11 answers

How to tell PowerShell to wait for each command to end before starting the next?

I have a PowerShell 1.0 script to just open a bunch of applications. The first is a virtual machine and the others are development applications. I want the virtual machine to finish booting before the rest of the applications are opened. In bash I…
John Mee
  • 50,179
  • 34
  • 152
  • 186
262
votes
9 answers

How to run a PowerShell script from a batch file

I am trying to run this script in PowerShell. I have saved the below script as ps.ps1 on my desktop. $query = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2" Register-WMIEvent -Query $query -Action { invoke-item "C:\Program…
Eka
  • 14,170
  • 38
  • 128
  • 212
262
votes
10 answers

How to redirect the output of a PowerShell to a file during its execution

I have a PowerShell script for which I would like to redirect the output to a file. The problem is that I cannot change the way this script is called. So I cannot do: .\MyScript.ps1 > output.txt How do I redirect the output of a PowerShell script…
Martin
  • 39,309
  • 62
  • 192
  • 278
260
votes
20 answers

How to get the current directory of the cmdlet being executed

This should be a simple task, but I have seen several attempts on how to get the path to the directory where the executed cmdlet is located with mixed success. For instance, when I execute C:\temp\myscripts\mycmdlet.ps1 which has a settings file at…
Stig Perez
  • 3,595
  • 4
  • 23
  • 36
259
votes
7 answers

.ps1 cannot be loaded because the execution of scripts is disabled on this system

I run this code to execute PowerShell code from an ASP.NET application: System.Management.Automation.Runspaces.Runspace runspace =…
umesh.chape
  • 2,895
  • 5
  • 16
  • 17
258
votes
6 answers

Reload the path in PowerShell

If I have an instance of PowerShell ISE running and I install something that modifies the PATH or I modify it in any way outside of PowerShell then I need to restart PowerShell for it to see the updated PATH variable. Is there a way to reload the…
rob
  • 17,995
  • 12
  • 69
  • 94
249
votes
7 answers

How to output something in PowerShell

I am running a PowerShell script from within a batch file. The script fetches a web page and checks whether the page's content is the string "OK". The PowerShell script returns an error level to the batch script. The batch script is executed by…
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
249
votes
4 answers

Invoke-WebRequest, POST with parameters

I'm attempting to POST to a uri, and send the parameter username=me Invoke-WebRequest -Uri http://example.com/foobar -Method POST How do I pass the parameters using the method POST?
kylex
  • 14,178
  • 33
  • 114
  • 175
248
votes
10 answers

Function return value in PowerShell

I have developed a PowerShell function that performs a number of actions involving provisioning SharePoint Team sites. Ultimately, I want the function to return the URL of the provisioned site as a String so at the end of my function I have the…
ChiliYago
  • 11,341
  • 23
  • 79
  • 126
237
votes
4 answers

How do you execute an arbitrary native command from a string?

I can express my need with the following scenario: Write a function that accepts a string to be run as a native command. It's not too far fetched of an idea: if you're interfacing with other command-line utilities from elsewhere in the company that…
Johnny Kauffman
  • 3,613
  • 3
  • 21
  • 22
237
votes
11 answers

How can I run PowerShell with the .NET 4 runtime?

I am updating a PowerShell script that manages some .NET assemblies. The script was written for assemblies built against .NET 2 (the same version of the framework that PowerShell runs with), but now needs to work with .NET 4 assemblies as well as…
Emperor XLII
  • 13,014
  • 11
  • 65
  • 75