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
121
votes
8 answers

Looping through a hash, or using an array in PowerShell

I'm using this (simplified) chunk of code to extract a set of tables from SQL Server with BCP. $OutputDirectory = 'c:\junk\' $ServerOption = "-SServerName" $TargetDatabase = "Content.dbo." $ExtractTables = @( "Page" ,…
Sylvia
  • 2,578
  • 9
  • 30
  • 37
121
votes
6 answers

Redirecting output to $null in PowerShell, but ensuring the variable remains set

I have some code: $foo = someFunction This outputs a warning message which I want to redirect to $null: $foo = someFunction > $null The problem is that when I do this, while successfully supressing the warning message, it also has the negative…
ted
  • 2,275
  • 5
  • 20
  • 17
121
votes
5 answers

Running CMD command in PowerShell

I am having a bunch of issues with getting a PowerShell command to run. All it is doing is running a command that would be run in a CMD prompt window. Here is the command: "C:\Program Files (x86)\Microsoft Configuration…
user3585839
  • 1,459
  • 3
  • 12
  • 18
121
votes
5 answers

Passing multiple values to a single PowerShell script parameter

I have a script to which I pass server name(s) in $args. This way I can do stuff to this (these) server(s) using foreach: .\script.ps1 host1 host2 host3 foreach ($i in $args) { Do-Stuff $i } I'd like to add a named optional parameter called…
jcarpio
  • 3,350
  • 5
  • 23
  • 22
120
votes
14 answers

How to normalize a path in PowerShell?

I have two paths: fred\frog and ..\frag I can join them together in PowerShell like this: join-path 'fred\frog' '..\frag' That gives me this: fred\frog\..\frag But I don't want that. I want a normalized path without the double dots, like…
dan-gph
  • 16,301
  • 12
  • 61
  • 79
118
votes
5 answers

Copy file remotely with PowerShell

I am writing a PowerShell script that I want to run from Server A. I want to connect to Server B and copy a file to Server A as a backup. If that can't be done then I would like to connect to Server B from Server A and copy a file to another…
chobo2
  • 83,322
  • 195
  • 530
  • 832
117
votes
7 answers

How to upgrade PowerShell version from 2.0 to 3.0

The OS that I am using is Windows 7, and the PowerShell version that is installed here is 2.0. Is it possible for me to upgrade it to version 3.0 or 4.0? Because there are cmdlets that version 2.0 can't recognize.
Teppie
  • 1,171
  • 2
  • 8
  • 3
116
votes
3 answers

GetType used in PowerShell, difference between variables

What is the difference between variables $a and $b? $a = (Get-Date).DayOfWeek $b = Get-Date | Select-Object DayOfWeek I tried to check $a.GetType $b.GetType MemberType : Method OverloadDefinitions : {type GetType()} TypeNameOfValue :…
jrara
  • 16,239
  • 33
  • 89
  • 120
114
votes
6 answers

Powershell - Why is Using Invoke-WebRequest Much Slower Than a Browser Download?

I use Powershell's Invoke-WebRequest method to download a file from Amazon S3 to my Windows EC2 instance. If I download the file using Chrome, I am able to download a 200 MB file in 5 seconds. The same download in PowerShell using Invoke-WebRequest…
Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
114
votes
10 answers

Why are my PowerShell scripts not running?

I wrote a simple batch file as a PowerShell script, and I am getting errors when they run. It's in a scripts directory in my path. This is the error I get: Cannot be loaded because the execution of scripts is disabled on this system. Please see…
DevelopingChris
  • 39,797
  • 30
  • 87
  • 118
113
votes
7 answers

Run bash script from Windows PowerShell

In cygwin, I could just do ./script.sh args, but this opens the script file in notepad in PowerShell. What do I need to do have it execute?
wsorenson
  • 5,701
  • 6
  • 32
  • 29
112
votes
5 answers

Post build event execute PowerShell

Is it possible to set up a .NET project with a post build event to execute a powershell script? I am using this script to generate some files. Also can I pass whether it's a debug or release build to script. An example of this would be great.
amateur
  • 43,371
  • 65
  • 192
  • 320
110
votes
8 answers

How to pass command-line arguments to a PowerShell ps1 file

For years, I have used the cmd/DOS/Windows shell and passed command-line arguments to batch files. For example, I have a file, zuzu.bat and in it, I access %1, %2, etc. Now, I want to do the same when I call a PowerShell script when I am in a…
Daniel 'Dang' Griffith
  • 1,641
  • 2
  • 13
  • 13
108
votes
2 answers

Creating a shadow copy using the "Backup" context in a PowerShell

I am in the process of writing a PowerShell script for backing up a Windows computer using rsync. To this end, I am attempting to use WMI from said script to create a non-persistent Shadow copy with writer participation (as is apparently recommended…
Julien Picalausa
  • 1,189
  • 1
  • 7
  • 3
108
votes
1 answer

PowerShell script not accepting $ (dollar) sign

I am trying to open an SQL data connection using a PowerShell script and my password contains a $ sign: $cn = new-object system.data.SqlClient.SqlConnection("Data Source=DBNAME;Initial Catalog=Catagory;User ID=User;Password=pass$word;") When I try…
Murtaza Mandvi
  • 10,708
  • 23
  • 74
  • 109