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
1 answer

Powershell Start Process, Wait with Timeout, Kill and Get Exit Code

I want to repeatedly execute a program in a loop. Sometimes, the program crashes, so I want to kill it so the next iteration can correctly start. I determine this via timeout. I have the timeout working but cannot get the Exit Code of the program,…
Andreas Reiff
  • 7,961
  • 10
  • 50
  • 104
21
votes
2 answers

Exit a PowerShell function but continue the script

This might seem like a very very stupid question, but I can't really figure it out. I'm trying to have the function stop when it finds its first hit (match) and then continue with the rest of the script. Code: Function Get-Foo { …
DarkLite1
  • 13,637
  • 40
  • 117
  • 214
21
votes
5 answers

Logging module not writing to file

I'm using logging module, and I've passed in the same parameters that I have on other jobs that are currently working: import logging from inst_config import config3 logging.basicConfig( level=logging.INFO, format='%(asctime)s…
flybonzai
  • 3,763
  • 11
  • 38
  • 72
21
votes
2 answers

Running remote GUI app in Powershell

We have a custom comonent that wraps some of the functionality of powershell so it can be used frim BizTalk 2006. For most operations (checking a file path, copy or move a file) this works fine. However we have the need to fire up a GUI app…
Stefan John Park
  • 211
  • 1
  • 2
  • 5
21
votes
3 answers

How to use a NuGet package within a PowerShell script?

I'm writing a PowerShell script that makes use of the Mono.Cecil library. How would I install the package so I can use it from within the script? Thanks! (For the record, I did try Googling before asking this, but all that came up was results about…
James Ko
  • 32,215
  • 30
  • 128
  • 239
21
votes
2 answers

Get Powershell command's output when invoked through code

I have written a piece of code (in C#) to execute a Powershell script (specifically Azure PowerShell) using System.Management.Automation. The powershell script basically uploads a vhd in a container on Azure, which shows the upload progress and time…
Muhammad Murad Haider
  • 1,357
  • 2
  • 18
  • 34
21
votes
2 answers

Ignore SSL warning with powershell downloadstring

I've got this beautiful one liner which calls a webservice of mine via Task Scheduler: -ExecutionPolicy unrestricted -Command "(New-Object Net.WebClient).DownloadString(\"https://127.0.0.1/xxx\")" But my webservice has SSL now and I want to make a…
Julian
  • 1,105
  • 2
  • 26
  • 57
21
votes
5 answers

How to get status of "Invoke-Expression", successful or failed?

Invoke-Expression will return all the text of the command being invoked. But how can I get the system return value of whether this command has been executed successfully or with a failure? In CMD I could use %errorlevel% to get external command…
vik santata
  • 2,989
  • 8
  • 30
  • 52
21
votes
3 answers

Find numbers after specific text in a string with RegEx

I have a multiline string like the following: 2012-15-08 07:04 Bla bla bla blup 2012-15-08 07:05 *** Error importing row no. 5: The import of this line failed because bla bla 2012-15-08 07:05 Another text that I don't want to search... 2012-15-08…
Patric
  • 2,789
  • 9
  • 33
  • 60
21
votes
5 answers

Set up PowerShell Script for Automatic Execution

I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options: One command line that opens PowerShell, executes script…
Yaakov Ellis
  • 40,752
  • 27
  • 129
  • 174
21
votes
1 answer

Powershell module: Dynamic mandatory hierarchical parameters

So what I really want is somewhat usable tab completion in a PS module. ValidateSet seems to be the way to go here. Unfortunately my data is dynamic, so I cannot annotate the parameter with all valid values…
Benjamin Podszun
  • 9,679
  • 3
  • 34
  • 45
21
votes
3 answers

Is the following possible in PowerShell: "Select-Object ."?

The scenario: I'm using Select-Object to access properties of a piped object, and one of those properties is itself an object. Let's call it PropertyObject. I want to access a property of that PropertyObject, say Property1. Is there any nice and…
Simon Elms
  • 17,832
  • 21
  • 87
  • 103
21
votes
3 answers

Powershellv2 - remove last x characters from a string

I have a file containing a few thousand lines of text. I need to extract some data from it, but the data I need is always 57 characters from the left, and 37 characters from the end. The bit I need (in the middle) is of varying length. e.g. …
IGGt
  • 2,627
  • 10
  • 42
  • 63
21
votes
4 answers

How to get PowerShell to wait for Invoke-Item completion?

How do I get PowerShell to wait until the Invoke-Item call has finished? I'm invoking a non-executable item, so I need to use Invoke-Item to open it.
arathorn
  • 2,098
  • 3
  • 20
  • 29
21
votes
4 answers

A positional parameter cannot be found that accepts argument '\'

I am trying to get the meta data from a directory and I am getting an error that A positional parameter cannot be found that accepts argument '\'. Not sure how to correct this? $FileMetadata = Get-FileMetaData -folder (Get-childitem $Folder1 + "\" +…
user1342164
  • 1,434
  • 13
  • 44
  • 83