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
154
votes
6 answers

What does the "@" symbol do in PowerShell?

I've seen the @ symbol used in PowerShell to initialise arrays. What exactly does the @ symbol denote and where can I read more about it?
GrahamMc
  • 3,034
  • 2
  • 24
  • 29
152
votes
7 answers

How can I see the command history across all PowerShell sessions in Windows Server 2016?

Where can you view the full history from all sessions in Windows Server 2016? The following PowerShell command only includes the commands from the current session: Get-History
Daniel Leach
  • 5,517
  • 4
  • 18
  • 32
151
votes
2 answers

Creating and throwing new exception

How I can create and throw a new exception in PowerShell? I want to do different things for a specific error.
user369182
  • 1,995
  • 4
  • 16
  • 17
151
votes
11 answers

Powershell v3 Invoke-WebRequest HTTPS error

Using Powershell v3's Invoke-WebRequest and Invoke-RestMethod I have succesfully used the POST method to post a json file to a https website. The command I'm using is $cert=New-Object…
floyd
  • 2,080
  • 4
  • 17
  • 19
150
votes
10 answers

Can Powershell Run Commands in Parallel?

I have a powershell script to do some batch processing on a bunch of images and I'd like to do some parallel processing. Powershell seems to have some background processing options such as start-job, wait-job, etc, but the only good resource I…
Alan Jackson
  • 6,361
  • 2
  • 31
  • 32
150
votes
17 answers

How to get disk capacity and free space of remote computer

I have this one-liner: get-WmiObject win32_logicaldisk -Computername remotecomputer and the output is this: DeviceID : A: DriveType : 2 ProviderName : FreeSpace : Size : VolumeName : DeviceID : C: DriveType :…
culter
  • 5,487
  • 15
  • 54
  • 66
149
votes
8 answers

A better way to check if a path exists or not in PowerShell

Is there a more concise and less error-prone way in PowerShell to check if a path DOES NOT exist? This is objectively too verbose for such a common use case: if (-not (Test-Path $path)) { ... } if (!(Test-Path $path)) { ... } It needs too many…
orad
  • 15,272
  • 23
  • 77
  • 113
148
votes
3 answers

How to run an application as "run as administrator" from the command prompt?

I have a batch file called test.bat. I am calling the below instructions in the test.bat file: start /min powershell.exe %sysdrive%\testScripts\testscript1.ps1 When I run this through the command prompt, my testscript is running successfully. I…
Praveen Jakkaraju
  • 1,601
  • 4
  • 16
  • 13
147
votes
9 answers

Change directory in PowerShell

My PowerShell prompt's currently pointed to my C drive (PS C:\>). How do I change directory to a folder on my Q (PS Q:\>) drive? The folder name on my Q drive is "My Test Folder".
SoConfused
  • 1,799
  • 3
  • 12
  • 18
147
votes
6 answers

PowerShell's Clear-History doesn't clear history

Recently I had to run a command that unfortunately required me to type a password right on the command line. Afterwards, I cleared my screen with "Clear", but also wanted to clear the command history so the offending command wouldn't show up in the…
Fopedush
  • 2,036
  • 4
  • 20
  • 22
147
votes
5 answers

How can you use an object's property in a double-quoted string?

I have the following code: $DatabaseSettings = @(); $NewDatabaseSetting = "" | select DatabaseName, DataFile, LogFile, LiveBackupPath; $NewDatabaseSetting.DatabaseName = "LiveEmployees_PD"; $NewDatabaseSetting.DataFile =…
caveman_dick
  • 6,302
  • 3
  • 34
  • 49
146
votes
3 answers

Multiline comment in PowerShell

Can we comment multiple lines together in PowerShell? I tried looking, but I didn't find any answer. It's quite irritating to comment each line manually if the script is too long.
Nipun
  • 2,217
  • 5
  • 23
  • 38
146
votes
15 answers

How can I uninstall an application using PowerShell?

Is there a simple way to hook into the standard 'Add or Remove Programs' functionality using PowerShell to uninstall an existing application? Or to check if the application is installed?
Rob Paterson
  • 2,493
  • 3
  • 21
  • 21
145
votes
6 answers

Path to Powershell.exe (v 2.0)

Where is the Powershell (version 2.0) located? What is the path to Powershell.exe? I have Windows Server 2008 and Powershell installed. When I look at this folder: PS C:\Windows\System32\WindowsPowerShell> dir Directory:…
jjoras
  • 2,001
  • 5
  • 18
  • 16
145
votes
8 answers

PowerShell Script to Find and Replace for all Files with a Specific Extension

I have several configuration files nested like such: C:\Projects\Project_1\project1.config C:\Projects\Project_2\project2.config In my configuration I need to do a string replace like such: will become:
Brandon
  • 10,744
  • 18
  • 64
  • 97