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
135
votes
10 answers

Extract the filename from a path

I want to extract filename from below path: D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv Now I wrote this code to get filename. This working fine as long as the folder level didn't change. But in case the folder level has been…
user664481
  • 2,141
  • 9
  • 25
  • 31
135
votes
9 answers

Timestamp on file name using PowerShell

I have a path in a string, C:\temp\mybackup.zip I would like insert a timestamp in that script, for example, C:\temp\mybackup 2009-12-23.zip Is there an easy way to do this in PowerShell?
Chris Jones
  • 2,630
  • 2
  • 21
  • 34
134
votes
1 answer

File extension for PowerShell 3

All of us probably know .bat for Batch files. But what is the file extension for PowerShell 3 scripts? I found .ps1 and some other endings but they're only for version 1.
ComFreek
  • 29,044
  • 18
  • 104
  • 156
133
votes
9 answers

Execute PowerShell Script from C# with Commandline Arguments

I need to execute a PowerShell script from within C#. The script needs commandline arguments. This is what I have done so far: RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace =…
Mephisztoe
  • 3,276
  • 7
  • 34
  • 48
131
votes
9 answers

Powershell: How can I stop errors from being displayed in a script?

When my PowerShell script tries, for example, to create a SQL Server object for a server that doesn't exist ("bla" in my case), PowerShell displays lots of PowerShell errors in red. Since my script checks the value of $? after such calls, and…
Andrew J. Brehm
  • 4,448
  • 8
  • 45
  • 70
129
votes
11 answers

How to pass boolean values to a PowerShell script from a command prompt

I have to invoke a PowerShell script from a batch file. One of the arguments to the script is a boolean value: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -File .\RunScript.ps1 -Turn 1 -Unify $false The command fails with…
mutelogan
  • 6,477
  • 6
  • 20
  • 15
129
votes
6 answers

How to replace multiple strings in a file using PowerShell

I am writing a script for customising a configuration file. I want to replace multiple instances of strings within this file, and I tried using PowerShell to do the job. It works fine for a single replace, but doing multiple replaces is very slow…
Ivo Bosticky
  • 6,338
  • 6
  • 34
  • 35
128
votes
2 answers

How to create a shortcut using PowerShell

I want to create a shortcut with PowerShell for this executable: C:\Program Files (x86)\ColorPix\ColorPix.exe How can this be done?
cethint
  • 2,231
  • 8
  • 28
  • 31
128
votes
1 answer

powershell 2.0 try catch how to access the exception

This is the try catch in PowerShell 2.0 $urls = "http://www.google.com", "http://none.greenjump.nl", "http://www.nu.nl" $wc = New-Object System.Net.WebClient foreach($url in $urls) { try { $url …
Medo
  • 1,435
  • 3
  • 10
  • 9
125
votes
4 answers

Convert a secure string to plain text

I'm working in PowerShell and I have code that successfully converts a user entered password into plain text: $SecurePassword = Read-Host -AsSecureString "Enter password" | convertfrom-securestring | out-file…
tmarsh
  • 1,355
  • 2
  • 9
  • 4
125
votes
3 answers

Running cURL on 64 bit Windows

I'm new to cURL, just got it installed but it seems to only do what it feels like. I'm using the 64 bit version I got from here: http://curl.haxx.se/latest.cgi?curl=win64-ssl-sspi with installation instructions I found here:…
Jonathon Nordquist
  • 2,066
  • 4
  • 21
  • 23
125
votes
8 answers

The term 'Get-ADUser' is not recognized as the name of a cmdlet

I have used the following query to list the users in a windows 2008 server, but failed and got the below error. $server='client-pc-1';$pwd= convertto-securestring 'password$' -asplaintext - force;$cred=new-object -typename…
Sebastian Xavier
  • 2,499
  • 7
  • 27
  • 41
124
votes
3 answers

Press any key to continue

According to Microsoft's documentation, read-host lets the user type some input, and then press enter to continue. Not exactly the correct behavior if you want to have "Press any key to continue". (Wait... where's the Any key?!) Is there a way to…
Jeff B
  • 8,572
  • 17
  • 61
  • 140
123
votes
12 answers

How can I get the current PowerShell executing file?

Note: PowerShell 1.0 I'd like to get the current executing PowerShell file name. That is, if I start my session like this: powershell.exe .\myfile.ps1 I'd like to get the string ".\myfile.ps1" (or something like that). EDIT: "myfile.ps1" is…
Ron Klein
  • 9,178
  • 9
  • 55
  • 88
123
votes
16 answers

Spaces cause split in path with PowerShell

I'm having an issue with powershell when invoking an exe at a path containing spaces. PS C:\Windows Services> invoke-expression "C:\Windows Services\MyService.exe" The term 'C:\Windows' is not recognized as the name of a cmdlet, function, script…
jaffa
  • 26,770
  • 50
  • 178
  • 289