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
107
votes
8 answers

How do I create a custom type in PowerShell for my scripts to use?

I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure: Contact { string First string Last string Phone } How…
Scott Saad
  • 17,962
  • 11
  • 63
  • 84
107
votes
8 answers

Safest way to run BAT file from Powershell script

I can not get a powershell script to execute a bat file directly. For example, this works on the command line: .\\my-app\my-fle.bat When I add this command to a script, it outputs: The term '.\\my-app\my-file.bat' is not recognized as the name of…
cmcginty
  • 113,384
  • 42
  • 163
  • 163
107
votes
6 answers

How to break lines in PowerShell?

I am [completely new to PowerShell and] concatenating a string in a loop, if a special condition occurs I should insert a line break...how can I do this? Basically looking for the equivalent of \n. $str = "" foreach($line in $file){ if($line…
user454322
  • 7,300
  • 5
  • 41
  • 52
106
votes
8 answers

PowerShell: how to grep command output?

In PowerShell I have tried: alias | select-string Alias This fails even though Alias is clearly in the output. I know this is because select-string is operating on some object and not the actual output string. What can be done about it?
Ian Kelling
  • 9,643
  • 9
  • 35
  • 39
106
votes
7 answers

PowerShell Set-Content and Out-File - what is the difference?

In PowerShell, what's the difference between Out-File and Set-Content? Or Add-Content and Out-File -append? I've found if I use both against the same file, the text is fully mojibaked. (A minor second question: > is an alias for Out-File, right?)
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
105
votes
6 answers

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

I'm trying to run a program from PowerShell, wait for the exit, then get access to the ExitCode, but I am not having much luck. I don't want to use -Wait with Start-Process, as I need some processing to carry on in the background. Here's a…
Richard
  • 29,854
  • 11
  • 77
  • 120
104
votes
5 answers

Powershell Get-ChildItem most recent file in directory

We produce files with date in the name. (* below is the wildcard for the date) I want to grab the last file and the folder that contains the file also has a date(month only) in its title. I am using PowerShell and I am scheduling it to run each day.…
user977645
  • 1,077
  • 2
  • 7
  • 10
104
votes
8 answers

Windows PowerShell: changing the command prompt

Using Windows PowerShell, how do I change the command prompt? For example, the default prompt says PS C:\Documents and Settings\govendes\My Documents> I want to customize that string.
sashang
  • 11,704
  • 6
  • 44
  • 58
104
votes
6 answers

How to convert string to integer in PowerShell

I have a list of directories with numbers. I have to find the highest number and and increment it by 1 and create a new directory with that increment value. I am able to sort the below array, but I am not able to increment the last element as it is…
Suman Ghosh
  • 1,317
  • 3
  • 12
  • 18
103
votes
6 answers

How to add more than one machine to the trusted hosts list using winrm

To run powershell commands on a machine from a remote machine we have to add the remote machine to the trusted hosts list of the host machine. I am adding machine A to machine B's trusted hosts using the following command : winrm set…
cmm user
  • 2,426
  • 7
  • 34
  • 48
103
votes
6 answers

PowerShell : retrieve JSON object by field value

Consider JSON in this format : "Stuffs": [ { "Name": "Darts", "Type": "Fun Stuff" }, { "Name": "Clean Toilet", "Type": "Boring Stuff" } ] In PowerShell 3, we can obtain a list of Stuffs : $JSON =…
BaltoStar
  • 8,165
  • 17
  • 59
  • 91
103
votes
1 answer

Difference between $? and $LastExitCode in PowerShell

In PowerShell, what is the difference between $? and $LastExitCode? I read about automatic variables, and it said: $? Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it…
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
102
votes
7 answers

How to Remove ReadOnly Attribute on File Using PowerShell?

How can I remove the ReadOnly attribute on a file, using a PowerShell (version 1.0) script?
Tangiest
  • 43,737
  • 24
  • 82
  • 113
102
votes
5 answers

Pass parameter from a batch file to a PowerShell script

In my batch file, I call the PowerShell script like this: powershell.exe "& "G:\Karan\PowerShell_Scripts\START_DEV.ps1" Now, I want to pass a string parameter to START_DEV.ps1. Let's say the parameter is w=Dev. How can I do this?
Karan
  • 3,265
  • 9
  • 54
  • 82
102
votes
3 answers

PowerShell string interpolation syntax

I always used the following syntax to be sure that variable were expanded in a string: "my string with a $($variable)" I recently ran into the following syntax: "my string with a ${variable}" Are they equivalent? Any difference?
fra
  • 3,488
  • 5
  • 38
  • 61