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
476
votes
21 answers

How to run an EXE file in PowerShell with parameters with spaces and quotes

How do you run the following command in PowerShell? C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data…
Vans
  • 4,769
  • 2
  • 16
  • 3
473
votes
15 answers

How do I get the current username in Windows PowerShell?

How do I get the current username in Windows PowerShell?
Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139
456
votes
15 answers

Unix tail equivalent command in Windows Powershell

I have to look at the last few lines of a large file (typical size is 500MB-2GB). I am looking for a equivalent of Unix command tail for Windows Powershell. A few alternatives available on are, http://tailforwin32.sourceforge.net/ and Get-Content…
mutelogan
  • 6,477
  • 6
  • 20
  • 15
447
votes
21 answers

How to recursively delete an entire directory with PowerShell 2.0?

What is the simplest way to forcefully delete a directory and all its subdirectories in PowerShell? I am using PowerShell V2 in Windows 7. I have learned from several sources that the most obvious command, Remove-Item $targetDir -Recurse -Force,…
Matt Spradley
  • 7,854
  • 9
  • 31
  • 40
432
votes
12 answers

How to search a string in multiple files and return the names of files in Powershell?

I have started learning powershell a couple of days ago, and I couldn't find anything on google that does what I need so please bear with my question. I have been asked to replace some text strings into multiple files. I do not necessarily know the…
Bluz
  • 5,980
  • 11
  • 32
  • 40
431
votes
20 answers

ps1 cannot be loaded because running scripts is disabled on this system

I try to run powershell script from c#. First i set the ExecutionPolicy to Unrestricted and the script is running now from PowerShell ISE. Now this is c# my code: class Program { private static PowerShell ps; static void Main(string[] args) …
user979033
  • 5,430
  • 7
  • 32
  • 50
424
votes
28 answers

Running a command as Administrator using PowerShell?

You know how if you're the administrative user of a system and you can just right click say, a batch script and run it as Administrator without entering the administrator password? I'm wondering how to do this with a PowerShell script. I do not want…
chrips
  • 4,996
  • 5
  • 24
  • 48
411
votes
13 answers

Is it possible to open a Windows Explorer window from PowerShell?

I'm sure this must be possible, but I can't find out how to do it. Any clues?
Lachmania
  • 4,613
  • 2
  • 20
  • 15
393
votes
18 answers

Is PowerShell ready to replace my Cygwin shell on Windows?

I'm debating whether I should learn PowerShell, or just stick with Cygwin/Perl scripts/Unix shell scripts, etc. The benefit of PowerShell would be that the scripts could be more easily used by teammates that don't have Cygwin; however, I don't know…
Andy White
  • 86,444
  • 48
  • 176
  • 211
388
votes
12 answers

How to stop a PowerShell script on the first error?

I want my PowerShell script to stop when any of the commands I run fail (like set -e in bash). I'm using both Powershell commands (New-Object System.Net.WebClient) and programs (.\setup.exe).
Andres Riofrio
  • 9,851
  • 7
  • 40
  • 60
388
votes
7 answers

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

I'm trying to execute this powershell command Invoke-WebRequest -Uri https://apod.nasa.gov/apod/ and I get this error. "Invoke-WebRequest : The request was aborted: Could not create SSL/TLS secure channel." https requests appear to work…
hewstone
  • 4,425
  • 2
  • 23
  • 24
385
votes
12 answers

Change the default terminal in Visual Studio Code

I am using Visual Studio Code on my Windows 10 PC. I want to change my default terminal from Windows PowerShell to Bash on Ubuntu (on Windows). How can I do that?
abhijeetps
  • 4,609
  • 4
  • 17
  • 30
370
votes
5 answers

How to print environment variables to the console in PowerShell?

I'm starting to use PowerShell and am trying to figure out how to echo a system environment variable to the console to read it. Neither of the below are working. The first just prints %PATH%, and the second prints nothing. echo %PATH% echo $PATH
kitfox
  • 4,534
  • 3
  • 17
  • 24
364
votes
19 answers

Using PowerShell to write a file in UTF-8 without the BOM

Out-File seems to force the BOM when using UTF-8: $MyFile = Get-Content $MyPath $MyFile | Out-File -Encoding "UTF8" $MyPath How can I write a file in UTF-8 with no BOM using PowerShell? Update 2021 PowerShell has changed a bit since I wrote this…
sourcenouveau
  • 29,356
  • 35
  • 146
  • 243
363
votes
14 answers

Ternary operator in PowerShell

From what I know, PowerShell doesn't seem to have a built-in expression for the so-called ternary operator. For example, in the C language, which supports the ternary operator, I could write something like: ? :…
mguassa
  • 4,051
  • 2
  • 14
  • 19