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
145
votes
9 answers

Referencing system.management.automation.dll in Visual Studio

I am beginning to look into the PowerShell model and snap-in development. The first thing I notice is to reference System.management.automation.dll. However in Visual Studio, the .NET tab does not have that assembly, and nor is one able browse to…
icelava
  • 9,787
  • 7
  • 52
  • 74
144
votes
7 answers

Does PowerShell support constants?

I would like to declare some integer constants in PowerShell. Is there any good way to do that?
Tom Hazel
  • 3,232
  • 2
  • 20
  • 20
143
votes
11 answers

Removing duplicate values from a PowerShell array

How can I remove duplicates from a PowerShell array? $a = @(1,2,3,4,5,5,6,7,8,9,0,0)
Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202
142
votes
11 answers

How do I concatenate two text files in PowerShell?

I am trying to replicate the functionality of the cat command in Unix. I would like to avoid solutions where I explicitly read both files into variables, concatenate the variables together, and then write out the concatenated variable.
merlin2011
  • 71,677
  • 44
  • 195
  • 329
142
votes
3 answers

What does "%" (percent) do in PowerShell?

It seems that the % operation starts script blocks after the pipeline, although about_Script_Blocks indicates the % isn't necessary. These all work just fine. get-childitem | % { write-host $_.Name } { write-host 'hello' } % { write-host 'hello'…
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
141
votes
18 answers

How do I check if a PowerShell module is installed?

To check if a module exists I have tried the following: try { Import-Module SomeModule Write-Host "Module exists" } catch { Write-Host "Module does not exist" } The output is: Import-Module : The specified module 'SomeModule' was not…
Klemens Schindler
  • 3,379
  • 3
  • 11
  • 11
141
votes
15 answers

How can I use PowerShell with the Visual Studio Command Prompt?

I've been using Beta 2 for a while now and it's been driving me nuts that I have to punt to cmd.exe when running the Visual Studio 2010 Command Prompt. I used to have a nice vsvars2008.ps1 script for Visual Studio 2008. Is there a vsvars2010.ps1…
Andy S
  • 8,641
  • 6
  • 36
  • 40
141
votes
3 answers

Getting the path of %AppData% in PowerShell

How can I get the path for the application data directory (e.g. C:\Users\User\AppData\Roaming) in PowerShell?
Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
140
votes
6 answers

How to list all properties of a PowerShell WMI object

When I look at the Win32_ComputerSystem class, it shows loads of properties like Status, PowerManagementCapabilities, etc. However, when in PowerShell I do the below I only get back a couple: PS C:\Windows\System32\drivers> Get-WmiObject -Class…
lara400
  • 4,646
  • 13
  • 46
  • 66
137
votes
10 answers

powershell - extract file name and extension

I need to extract file name and extension from e.g. my.file.xlsx. I don't know the name of file or extension and there may be more dots in the name, so I need to search the string from the right and when I find first dot (or last from the left),…
culter
  • 5,487
  • 15
  • 54
  • 66
137
votes
12 answers

How to get the Parent's parent directory in Powershell?

So if I have a directory stored in a variable, say: $scriptPath = (Get-ScriptDirectory); Now I would like to find the directory two parent levels up. I need a nice way of doing: $parentPath = Split-Path -parent $scriptPath $rootPath = Split-Path…
Mark Kadlec
  • 8,036
  • 17
  • 60
  • 96
137
votes
18 answers

How can you test if an object has a specific property?

How can you test if an object has a specific property? Appreciate I can do ... $members = Get-Member -InputObject $myobject and then foreach through the $members, but is there a function to test if the object has a specific property? Additional…
SteveC
  • 15,808
  • 23
  • 102
  • 173
136
votes
19 answers

How to fix error- nodemon.ps1 cannot be loaded because running scripts is disabled on this system, (without security risk)?

Error on terminal: nodemon.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies…
136
votes
23 answers

VSC PowerShell. After npm updating packages .ps1 cannot be loaded because running scripts is disabled on this system

I design websites in VSC and PowerShell is my default terminal. After updating and deploying a website to firebase earlier, I was prompted to update firebase tools - which I did using npm. Immediately after I cannot run/access any firebase scripts…
Aponting
  • 1,361
  • 2
  • 7
  • 6
135
votes
9 answers

How do you do a ‘Pause’ with PowerShell 2.0?

OK, I'm losing it. PowerShell is annoying me. I'd like a pause dialog to appear, and it won't. PS W:\>>> $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exception calling "ReadKey" with "1" argument(s): "The method or operation is not…
Derrick Bell
  • 2,615
  • 3
  • 26
  • 30