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

Powershell Invoke-RestMethod Authorization Header

While invoking an Invoke-RestMethod using Powershell like: Invoke-RestMethod -Method Get -Uri "https://google.com/api/GetData" -Headers $headers and $headers being $headers = @{ Authorization="Secret $username $password" …
20
votes
3 answers

grep and sed equivalent in PowerShell

I am trying to do the following statement in PowerShell svn info filename | grep '^Last Changed Date:'| sed -e 's/^Last Changed Date: //' I have tried this: svn info filename | Select-String '^Last Changed Date:' I am expecting below…
script0207
  • 345
  • 1
  • 4
  • 12
20
votes
5 answers

Powershell Color Schemes?

Is there a place where I can find Powershell Color Schemes that people have already built? Something like https://github.com/lysyi3m/osx-terminal-themes, but for Windows Powershell instead of OSX. I did find this one:…
wheeeee
  • 1,046
  • 2
  • 14
  • 33
20
votes
3 answers

Use the Get-Help cmdlet to display comment-based help in the same format

I am trying to use the Get-Help cmdlet to display comment-based help in the same format in which it displays the cmdlet help topics that are generated from XML files. The ability to do this is documented in about_Comment_based_Help on TechNet, but…
Shaun
  • 436
  • 1
  • 5
  • 10
20
votes
2 answers

How can I find the Upgrade Code for an installed MSI file?

In certain cases the need to retrieve MSI upgrade codes for deployed packages can arise. Common scenarios: I took over someone else's MSI project, and I need to determine what upgrade codes were used for previous versions that are already in the…
Stein Åsmul
  • 39,960
  • 25
  • 91
  • 164
20
votes
8 answers

Enable Windows 10 built-in hotspot by cmd/batch/powershell

I'm searching for a way to enable/disable the Hotspot built into Windows 10 via the command prompt, powershell or a batch file. In the GUI, it can be easily done with the third button in the network panel (see image below), but I want to automate…
casiosmu
  • 797
  • 1
  • 8
  • 22
20
votes
6 answers

virtualenv hung up on installing setuptools

never had this issue until just recently, but when trying to create a new virtual environment (windows 7, python 2.7.13, virtualenv==15.1.0) it just hangs on "Installing setuptools, pip, wheel..." and doing a crtl^c gives you this: PS…
John
  • 359
  • 1
  • 3
  • 9
20
votes
2 answers

How to start powershell with a specific window size from RUN?

How to start a powershell from "RUN" with specific window size? is there any argument for that like "-size:100x100". is that possible with RUN or is there any other way to run a program window with a given size?
knobiDev
  • 462
  • 1
  • 5
  • 17
20
votes
2 answers

How can I "zip" two arrays in PowerShell?

I want to zip two arrays, like how Ruby does it, but in PowerShell. Here's a hypothetical operator (I know we're probably talking about some kind of goofy pipeline, but I just wanted to show an example output). PS> @(1, 2, 3) -zip @('A', 'B',…
Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
20
votes
6 answers

Why is Copy-Item overwriting destination files by default?

The behaviour I would expect from the code below is: Grab a list of the files in the source directory. Loop through and copy each file to the backup destination, only if it does not already exist. if (!(Test-Path C:\Folder\Destination)) { …
Supernatix
  • 465
  • 2
  • 4
  • 14
20
votes
5 answers

Login-AzureRmAccount : The term 'Login-AzureRmAccount' is not recognized as the name of a cmdlet, function, script

I'm having an issue with Azure PS modules. I have installed via PS gallery with the following: Install-Module AzureRM Install-Module Azure (And restarted) However, when I run Login-AzureRmAccount I get the following error: Login-AzureRmAccount :…
Nagoh
  • 813
  • 2
  • 10
  • 23
20
votes
3 answers

Powershell Get-WebSite name parameter is ignored

I want to retrieve information regarding specific IIS 7 website using the PowerShell Get-Website cmdlet. Unfortunately, Get-Website returns information for all websites regardless of the -Name parameter I pass in. It appears that the -Name…
Ryan Taylor
  • 8,740
  • 15
  • 65
  • 98
20
votes
4 answers

powershell mandatory parameter with default value shown

I am looking for a way to have an PowerShell script ask for an parameter which needs to be mandatory, but shown with an default value, e.g.: .\psscript Supply values for the following parameters: parameter1[default value]: …
Alex Flora
  • 203
  • 1
  • 2
  • 4
20
votes
6 answers

Get CPU temperature in CMD/POWER Shell

In my computer I am trying to get the CPU temperature. Searching on StackOverflow I found this: C:\WINDOWS\system32>wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature But I get this error: Node -…
utkroza blue
  • 201
  • 1
  • 2
  • 3
20
votes
4 answers

How to declare an array of strings (on multiple lines)

Why does $dlls.Count return a single element? I try to declare my array of strings as such: $basePath = Split-Path $MyInvocation.MyCommand.Path $dlls = @( $basePath + "\bin\debug\dll1.dll", $basePath + "\bin\debug\dll2.dll", $basePath +…
Bruno
  • 4,685
  • 7
  • 54
  • 105