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
237
votes
3 answers

Array.Add vs +=

I've found some interesting behaviour in PowerShell Arrays, namely, if I declare an array as: $array = @() And then try to add items to it using the $array.Add("item") method, I receive the following error: Exception calling "Add" with "1"…
malgca
  • 2,707
  • 2
  • 16
  • 9
236
votes
20 answers

How to get an MD5 checksum in PowerShell

I would like to calculate an MD5 checksum of some content. How do I do this in PowerShell?
Luke101
  • 63,072
  • 85
  • 231
  • 359
234
votes
4 answers

Prompt for user input in PowerShell

I want to prompt the user for a series of inputs, including a password and a filename. I have an example of using host.ui.prompt, which seems sensible, but I can't understand the return. Is there a better way to get user input in PowerShell?
AJ.
  • 13,461
  • 19
  • 51
  • 63
234
votes
4 answers

PowerShell and the -contains operator

Consider the following snippet: "12-18" -Contains "-" You’d think this evaluates to true, but it doesn't. This will evaluate to false instead. I’m not sure why this happens, but it does. To avoid this, you can use this…
tnw
  • 13,521
  • 15
  • 70
  • 111
231
votes
9 answers

PowerShell: Setting an environment variable for a single command only

On Linux, I can do: $ FOO=BAR ./myscript to call "myscript" with the environment variable FOO being set. Is something similar possible in PowerShell, i.e. without having to first set the variable, call the command, and then unset the variable…
miracle2k
  • 29,597
  • 21
  • 65
  • 64
229
votes
13 answers

How to format a DateTime in PowerShell

I can format the Get-Date cmdlet no problem like this: $date = Get-Date -format "yyyyMMdd" But once I've got a date in a variable, how do I format it? The statement below $dateStr = $date -format "yyyMMdd" returns this error: "You must provide a…
Ev.
  • 7,109
  • 14
  • 53
  • 87
227
votes
11 answers

Delete files older than 15 days using PowerShell

I would like to delete only the files that were created more than 15 days ago in a particular folder. How could I do this using PowerShell?
user2470170
  • 2,320
  • 2
  • 13
  • 8
224
votes
13 answers

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

I want call execution for a myScript1.ps1 script inside a second myScript2.ps1 script inside Powershell ISE. The following code inside MyScript2.ps1, works fine from Powershell Administration, but doesn't work inside PowerShell ISE: #Call myScript1…
Nicola C.
  • 2,717
  • 3
  • 18
  • 25
224
votes
28 answers

Visual studio code cmd error: Cannot be loaded because running scripts is disabled on this system

Inside of visual studio code, I'm trying to execute a script.bat from the command line, but I'm getting the following error: File C:\Theses_Repo\train-cnn\environment\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this…
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
224
votes
8 answers

Powershell equivalent of bash ampersand (&) for forking/running background processes

In bash the ampersand (&) can be used to run a command in the background and return interactive control to the user before the command has finished running. Is there an equivalent method of doing this in Powershell? Example of usage in bash: sleep…
Eddie Groves
  • 33,851
  • 14
  • 47
  • 48
223
votes
25 answers

How to run a PowerShell script without displaying a window?

How is it possible to run a PowerShell script without displaying a window or any other sign to the user? In other words, the script should run quietly in the background without any sign to the user. Extra credit for an answer that does not use third…
Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139
221
votes
17 answers

PowerShell script to return versions of .NET Framework on a machine?

What would a PowerShell script be to return versions of the .NET Framework on a machine? My first guess is something involving WMI. Is there something better? It should be a one-liner to return only the latest version for each installation of .NET…
MattUebel
  • 2,737
  • 4
  • 21
  • 22
218
votes
9 answers

PowerShell equivalent to grep -f

I'm looking for the PowerShell equivalent to grep --file=filename. If you don't know grep, filename is a text file where each line has a regular expression pattern you want to match. Maybe I'm missing something obvious, but Select-String doesn't…
Fordio
  • 3,410
  • 2
  • 14
  • 18
216
votes
6 answers

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

There are a number of different ways to output messages. What is the effective difference between outputting something via Write-Host, Write-Output, or [console]::WriteLine? I also notice that if I use: write-host "count=" + $count The + gets…
Scott Langham
  • 58,735
  • 39
  • 131
  • 204
216
votes
22 answers

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

I am distributing a PowerShell script to my team. The script is to fetch an IP address from the Vsphere client, make an mstsc connection, and log it in a shared file. The moment they used the script they got to know the IP address of machine. After…
Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230