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
363
votes
15 answers

How can I replace every occurrence of a String in a file with PowerShell?

Using PowerShell, I want to replace all exact occurrences of [MYID] in a given file with MyValue. What is the easiest way to do so?
amateur
  • 43,371
  • 65
  • 192
  • 320
360
votes
4 answers

How do I negate a condition in PowerShell?

How do I negate a conditional test in PowerShell? For example, if I want to check for the directory C:\Code, I can run: if (Test-Path C:\Code){ write "it exists!" } Is there a way to negate that condition, e.g. (non-working): if (Not (Test-Path…
Ben McCormack
  • 32,086
  • 48
  • 148
  • 223
358
votes
17 answers

How to quietly remove a directory with content in PowerShell

Using PowerShell, is it possible to remove some directory that contains files without prompting to confirm action?
hsz
  • 148,279
  • 62
  • 259
  • 315
337
votes
11 answers

Echo equivalent in PowerShell for script testing

I would like to output variables and values out in a PowerShell script by setting up flags and seeing the data matriculate throughout the script. How would I do this? For example, what would be the PowerShell equivalent to the following PHP code?…
phill
  • 13,434
  • 38
  • 105
  • 141
335
votes
4 answers

Loop through files in a directory using PowerShell

How can I change the following code to look at all the .log files in the directory and not just the one file? I need to loop through all the files and delete all lines that do not contain "step4" or "step9". Currently this will create a new file,…
user2725402
  • 4,349
  • 7
  • 24
  • 23
330
votes
8 answers

Why powershell does not run Angular commands?

I have started to learn Angular but I note that powershell in Windows gives me an error whenever I make an angular command like: ng new new-app or ng serve this is the error what I got: ng : File C:\Users\< username >\AppData\Roaming\npm\ng.ps1…
Amir Makram
  • 12,030
  • 3
  • 13
  • 25
324
votes
11 answers

Creating hard and soft links using PowerShell

Can PowerShell 1.0 create hard and soft links analogous to the Unix variety? If this isn't built in, can someone point me to a site that has a ps1 script that mimics this? This is a necessary function of any good shell, IMHO. :)
Mike T
  • 3,696
  • 4
  • 21
  • 21
323
votes
10 answers

Recursive file search using PowerShell

I am searching for a file in all the folders. Copyforbuild.bat is available in many places, and I would like to search recursively. $File = "V:\Myfolder\**\*.CopyForbuild.bat" How can I do it in PowerShell?
Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230
322
votes
8 answers

How to split long commands over multiple lines in PowerShell

How do you take a command like the following in PowerShell and split it across multiple lines? &"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" -verb:sync -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web"…
asgerhallas
  • 16,890
  • 6
  • 50
  • 68
319
votes
10 answers

Timing a command's execution in PowerShell

Is there a simple way to time the execution of a command in PowerShell, like the 'time' command in Linux? I came up with this: $s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds But I would like something simpler like time…
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
318
votes
8 answers

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

I have a .ps1 file in which I want to define custom functions. Imagine the file is called MyFunctions.ps1, and the content is as follows: Write-Host "Installing functions" function A1 { Write-Host "A1 is running!" } Write-Host "Done" To run…
willem
  • 25,977
  • 22
  • 75
  • 115
315
votes
10 answers

How to unzip a file in Powershell?

I have a .zip file and need to unpack its entire content using Powershell. I'm doing this but it doesn't seem to work: $shell = New-Object -ComObject shell.application $zip = $shell.NameSpace("C:\a.zip") MkDir("C:\a") foreach ($item in $zip.items())…
Uli Kunkel
  • 3,485
  • 3
  • 12
  • 8
313
votes
11 answers

How to create permanent PowerShell Aliases

I want to create an alias of a cmdlet that doesn't expire after I close the current session of Powershell, let's say I have this alias : C:\Users\Aymen> New-Alias Goto Set-Location This perfectly creates the Goto alias, but I want to use it even…
AymenDaoudi
  • 7,811
  • 9
  • 52
  • 84
298
votes
17 answers

How do I get only directories using Get-ChildItem?

I'm using PowerShell 2.0 and I want to pipe out all the subdirectories of a certain path. The following command outputs all files and directories, but I can't figure out how to filter out the files. Get-ChildItem c:\mypath -Recurse I've tried using…
Peter Hull
  • 6,683
  • 4
  • 39
  • 48
298
votes
22 answers

How do I start PowerShell from Windows Explorer?

Is there a way to start PowerShell in a specific folder from Windows Explorer, e.g. to right-click in a folder and have an option like "Open PowerShell in this Folder"? It's really annoying to have to change directories to my project folder the…
Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148