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
188
votes
6 answers

How to get an object's property's value by property name?

In PowerShell, how do you get an object's property value by specifying its name (a string)? I want something like the following: $obj = get-something # View the object's members: $obj | gm # I could retrieve a property by doing so: write-host…
KFL
  • 17,162
  • 17
  • 65
  • 89
187
votes
5 answers

Select the values of one property on all objects of an array in PowerShell

Let's say we have an array of objects $objects. Let's say these objects have a "Name" property. This is what I want to do $results = @() $objects | %{ $results += $_.Name } This works, but can it be done in a better way? If I do something like:…
Sylvain Reverdy
  • 2,468
  • 3
  • 16
  • 14
186
votes
16 answers

How do you set PowerShell's default directory?

Is there a way to change PowerShell's default location? How do you set PowerShell's default working directory?
Youbloodywombat
  • 2,087
  • 2
  • 13
  • 10
185
votes
22 answers

Get Folder Size from Windows Command Line

Is it possible in Windows to get a folder's size from the command line without using any 3rd party tool? I want the same result as you would get when right clicking the folder in the windows explorer → properties.
Eldad Assis
  • 10,464
  • 11
  • 52
  • 78
184
votes
7 answers

Printing object properties in Powershell

When working in the interactive console if I define a new object and assign some property values to it like this: $obj = New-Object System.String $obj | Add-Member NoteProperty SomeProperty "Test" Then when I type the name of my variable into the…
John
  • 2,715
  • 3
  • 17
  • 20
182
votes
11 answers

Get file version in PowerShell

How can you get the version information from a .dll or .exe file in PowerShell? I am specifically interested in File Version, though other version information (that is, Company, Language, Product Name, etc.) would be helpful as well.
Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
180
votes
6 answers

When should I use Write-Error vs. Throw? Terminating vs. non-terminating errors

Looking at a Get-WebFile script over on PoshCode, http://poshcode.org/3226, I noticed this strange-to-me contraption: $URL_Format_Error = [string]"..." Write-Error $URL_Format_Error return What is the reason for this as opposed to the…
Bill Barry
  • 3,423
  • 2
  • 24
  • 22
180
votes
34 answers

How to find the Windows version from the PowerShell command line

How do I find which Windows version I'm using? I'm using PowerShell 2.0 and tried: PS C:\> ver The term 'ver' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was…
jrara
  • 16,239
  • 33
  • 89
  • 120
180
votes
5 answers

Read file line by line in PowerShell

I want to read a file line by line in PowerShell. Specifically, I want to loop through the file, store each line in a variable in the loop, and do some processing on the line. I know the Bash equivalent: while read line do if [[ $line =~ $regex…
Kingamere
  • 9,496
  • 23
  • 71
  • 110
180
votes
7 answers

How to count objects in PowerShell?

As I'm reading in the PowerShell user guide, one of the core PowerShell concepts is that commands accept and return objects instead of text. So for example, running get-alias returns me a number of System.Management.Automation.AliasInfo objects: PS…
ulidtko
  • 14,740
  • 10
  • 56
  • 88
178
votes
34 answers

Can't install nuget package because of "Failed to initialize the PowerShell host"

All of a sudden, I am getting this error when upgrading Nuget packages. None of the fixes that I have come across work. I am using Visual Studio 2013. 'Newtonsoft.Json 6.0.3' already installed. Adding 'Newtonsoft.Json 6.0.3' to…
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341
177
votes
7 answers

PowerShell: Run command from script's directory

I have a PowerShell script that does some stuff using the script’s current directory. So when inside that directory, running .\script.ps1 works correctly. Now I want to call that script from a different directory without changing the referencing…
poke
  • 369,085
  • 72
  • 557
  • 602
176
votes
15 answers

Check if a Windows service exists and delete in PowerShell

I am currently writing a deployment script that installs a number of Windows services. The services names are versioned, so I want to delete the prior Windows service version as part of the installs of the new service. How can I best do this in…
Adrian Russell
  • 3,995
  • 5
  • 25
  • 26
176
votes
7 answers

Check if a file exists or not in Windows PowerShell?

I have this script which compares files in two areas of the disk and copies the latest file over the one with the older modified date. $filestowatch=get-content C:\H\files-to-watch.txt $adminFiles=dir C:\H\admin\admin -recurse | ? {…
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
174
votes
3 answers

Changing PowerShell's default output encoding to UTF-8

By default, when you redirect the output of a command to a file or pipe it into something else in PowerShell, the encoding is UTF-16, which isn't useful. I'm looking to change it to UTF-8. It can be done on a case-by-case basis by replacing the…
rwallace
  • 31,405
  • 40
  • 123
  • 242