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
22
votes
2 answers

How do you add more property values to a custom object

If I do this $account = New-Object -TypeName psobject -Property @{User="Jimbo"; Password="1234"} How do I add additional User and Password values to $account without overwriting the existing one? I cannot pre-populate $account from a hashtable. I…
eodeluga
  • 608
  • 2
  • 7
  • 20
22
votes
1 answer

Filtering output using "Where-Object" in Powershell

I'm trying to get into PowerShell and have encountered my first hurdle. when I run Get-Command | Where-Object CommandType -contains Cmdlet My output gets filtered so that only commands with "CommandType" property value containing "Cmdlet" gets…
Jack Pettersson
  • 1,606
  • 4
  • 17
  • 28
22
votes
9 answers

How to run an application as shell replacement on Windows 10 Enterprise

I need to create a special account on a computer running Windows 10 Enterprise. This account would launch an application directly on login instead of the default shell and exiting the application should force the computer to restart. I was able to…
Jozef Legény
  • 1,157
  • 1
  • 11
  • 26
22
votes
2 answers

How to launch PowerShell script from the OS command line?

I have a PowerShell script for building my project files, and I'd like to have capability to run it from my file manager's command line (and, possibly, make a shortcut to this script so I can start build from my desktop) Any way to do this?
skevar7
  • 995
  • 1
  • 10
  • 21
22
votes
2 answers

Windows user environment variable vs. system environment variable

In Windows, is there any shell/PowerShell command to list user environment variable and system environment variable separately? If I do - SET TEMP Windows displays the user environment variable instead of system variable for TEMP. I am looking for…
thinkster
  • 586
  • 2
  • 5
  • 19
22
votes
3 answers

Multiple parameter sets and PowerShell

I am building a function which will have three distinct parameter sets, and two of those sets will overlap with the third. The options would look like this: A B A C A (D E F) A B (D E F) A C (D E F) To make it a little more clear, here is a…
user4872340
22
votes
4 answers

Executing PowerShell Commands in Java Program

I have a PowerShell Command which I need to execute using Java program. Can somebody guide me how to do this? My command is Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName,…
question
  • 392
  • 1
  • 4
  • 15
22
votes
4 answers

Powershell Write-Host append to text file - computer name and time stamp

I am a Powershell noobie and I am currently writing my second script so bear with me. I am trying to do a write-host and output my write-host message along with a time stamp and what computer is completing my various script blocks to a text file and…
h34th3r
  • 221
  • 1
  • 2
  • 3
22
votes
5 answers

PowerShell's pipe adds linefeed

I'm trying to pipe a string into a program's STDIN without any trailing linefeeds (unless that string itself actually ends in a linefeed). I tried googling around, but I only found people trying to print to the console without a trailing linefeed,…
Martin Ender
  • 43,427
  • 11
  • 90
  • 130
22
votes
8 answers

How to detect if Azure Powershell session has expired?

I'm writing an Azure PowerShell script and to login to Azure I call Add-AzureAccount which will popup a browser login window. I'm wondering what's the best way to check if the authentication credentials have expired or not and thus if I should call…
Johan Paul
  • 2,203
  • 2
  • 22
  • 38
22
votes
3 answers

PowerShell 2.0 ConvertFrom-Json and ConvertTo-Json implementation

I would like to monkeypatch a PowerShell 2.0 environment where the upgrade to 3.0 is not possible at this time. I am looking for a PowerShell 2.0 script implementation of the ConvertFrom-Json cmdlet and ConvertTo-Json cmdlet that are in PowerShell…
Josh Petitt
  • 9,371
  • 12
  • 56
  • 104
22
votes
1 answer

Powershell string does not contain

I have some code that takes in a string, Foreach($user in $allUsers){ if($user.DisplayName.ToLower().Contains("example.com") -or $user.DisplayName.ToLower()) { } else { $output3 = $externalUsers.Rows.Add($user.DisplayName) …
Grady D
  • 1,889
  • 6
  • 30
  • 61
22
votes
3 answers

What does (?ms) in Regex mean?

I have following Regex in Powershell : [regex]$regex = @' (?ms).*?
.*? '@ What does (?ms) mean here.
Powershel
  • 615
  • 4
  • 11
  • 18
22
votes
2 answers

Out-File -append in Powershell does not produce a new line and breaks string into characters

I'm trying to understand some weird behaviour with this cmdlet. If I use "Out-File -append Filename.txt" on a text file that I created and entered text into via the windows context menu, the string will append to the last line in that file as a…
BSAFH
  • 725
  • 3
  • 6
  • 19
22
votes
4 answers

Set location of Special Folders with PowerShell

As administrator, I want to change the default location of special folders (Documents, Music, Downloads…) to a different path. I can do this manually, but I would like to have a PowerShell script to do that. Is there any PS Object that provides…
SuperJMN
  • 13,110
  • 16
  • 86
  • 185