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

Maximize window and bring it in front with powershell

Is there a way to bring a window in front from powershell? I tried this to hide all windows (working) and bring me the powershell back (not working) [void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic") $shell =…
Yots
  • 1,655
  • 6
  • 17
  • 25
21
votes
4 answers

Powershell equivalent of python's if __name__ == '__main__':

I am really fond of python's capability to do things like this: if __name__ == '__main__': #setup testing code here #or setup a call a function with parameters and human format the output #etc... This is nice because I can treat a…
Mark Mascolino
  • 2,227
  • 1
  • 15
  • 19
21
votes
3 answers

How do I avoid getting data printed to stdout in my return value?

In doing some Powershell automation, I'm having trouble with the way that data written to stdout by a .cmd file is automatically captured. I have two functions that do something like the following: function a { & external.cmd # prints "foo" …
JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
21
votes
3 answers

How do I escape "Quotes" in a powershell string?

I need to send a simple string to a web api using Powershell, and I have to ensure the value in the HTML body has "Quotes" around it, because the content type has to be application/json. For example: $specialKey = "101010" Invoke-RestMethod -Method…
willem
  • 25,977
  • 22
  • 75
  • 115
21
votes
3 answers

Creating powershell modules from multiple files, referencing with module

I creating a PowerShell script module using separate source files. What is the canonical way to reference source functions internal to the module from other internal source files? For example if my module is created from PS source code in files…
Dweeberly
  • 4,668
  • 2
  • 22
  • 41
21
votes
6 answers

Use PowerShell for Visual Studio Command Prompt

In a serious intiative to migrate all my command line operations to PowerShell, I would like to avoid using the old fashioned command console for anything. However, the Visual Studio Command prompt has various environment variables and path…
ProfK
  • 49,207
  • 121
  • 399
  • 775
21
votes
6 answers

List files with path and file size only in Command Line

Windows Command Line (or maybe PowerShell). How can I list all files, recursively, with full path and filesize, but without anything else and export to a .txt file. Much preferably a code that works for whichever current directory I am in with the…
user3026965
  • 673
  • 4
  • 8
  • 22
21
votes
2 answers

Change XML Element value with PowerShell

I'm only finding stuff on how to change the attribute values of a XML element here on StackOverflow. But how do we change the value of the element itself using PowerShell? I currently have: XML ...
Kahn Kah
  • 1,389
  • 7
  • 24
  • 49
21
votes
1 answer

Unquoted tokens in argument mode involving variable references and subexpressions: why are they sometimes split into multiple arguments?

Note: A summary of this question has since been posted at the PowerShell GitHub repository, since superseded by this more comprehensive issue. Arguments passed to a command in PowerShell are parsed in argument mode (as opposed to expression mode -…
mklement0
  • 382,024
  • 64
  • 607
  • 775
21
votes
3 answers

Is there any way to invoke PowerQuery/M outside of Excel or PowerBI?

Our BI team is really growing to like the Power Query ETL tool used within Excel and Power BI. The functional language M/PowerQuery has great utility and it would be nice to be able to utilize outside of the context of PowerBI. Is there or are there…
dkackman
  • 15,179
  • 13
  • 69
  • 123
21
votes
3 answers

Extract data from System.Data.DataRow in powershell

I have a powershell script that executes an sql command and returns a list of ID numbers. When I iterate through the list, this is what it returns.…
cyberbemon
  • 3,000
  • 11
  • 37
  • 62
21
votes
3 answers

PowerShell: how to delete a path in the Path environment variable

I used "setx" to add a new path to my PATH environment variable. How do I see whether we can delete the newly added path from PATH environment variable?
derek
  • 9,358
  • 11
  • 53
  • 94
21
votes
3 answers

Displaying block of text

I've done a bit of Googling and can't seem to find an effective method of displaying an entire block of text to the console. I would rather not use the Write-Host command on every line if I need to display a block of code. I'm trying to make an…
cloudnyn3
  • 769
  • 4
  • 10
  • 15
21
votes
4 answers

Powershell command to trim path if it ends with "\"

I need to trim path if it ends with \. C:\Ravi\ I need to change to C:\Ravi I have a case where path will not end with \ (Then it must skip). I tried with .EndsWith("\"), but it fails when I have \\ instead of \. Can this be done in PowerShell…
Ravichandra
  • 2,162
  • 4
  • 24
  • 36
21
votes
2 answers

How to handle backslash character in PowerShell -replace string operations?

I am using -replace to change a path from source to destination. However I am not sure how to handle the \ character. For example: $source = "\\somedir" $dest = "\\anotherdir" $test = "\\somedir\somefile" $destfile = $test -replace $source,…
timanderson
  • 843
  • 1
  • 10
  • 20