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
5 answers

Output binary data on PowerShell pipeline

I need to pipe some data to a program's stdin: First 4 bytes are a 32-bit unsigned int representing the length of the data. These 4 bytes are exactly the same as C would store an unsigned int in memory. I refer to this as binary data. Remaining…
johnnycrash
  • 5,184
  • 5
  • 34
  • 58
21
votes
1 answer

PowerShell XML SelectNodes fails to process XPath

I want to get a list of all project references in my csproj file using PowerShell. Currently I've the following approach: [xml]$csproj = Get-Content MyProject.csproj $refs = $csproj.SelectNodes("//ProjectReference") foreach($ref in $refs) { #…
D.R.
  • 20,268
  • 21
  • 102
  • 205
21
votes
5 answers

Hashtables from ConvertFrom-json have different type from powershells built-in hashtables, how do I make them the same?

I have a json file (test.json) that looks something like this: { "root": { "key":"value" } } I'm loading it into powershell using something like this: PS > $data = [System.String]::Join("",…
brad
  • 2,221
  • 3
  • 24
  • 26
21
votes
8 answers

Is there a command for checking alias existence in PowerShell?

Is there a PowerShell command that allows you to check to see if an alias exists or not? (I have been looking around on the web, and it doesn't look like it.)
IbrarMumtaz
  • 4,235
  • 7
  • 44
  • 63
21
votes
1 answer

Difference between PowerShell Console and PowerShell ISE

What are differences between PowerShell Console and PowerShell ISE. I am asking this question in context of Profiles in PowerShell. Because PowerShell Console and PowerShell ISE both have differnet profiles.
daniyalahmad
  • 3,513
  • 8
  • 29
  • 52
21
votes
1 answer

Add new metadata properties to a file

I want to add some metadata properties to some files. Just like there are Owner, Computer, Title, Subject, etc for doc files, I want to be able to add some custom attributes. How can that be done?
user2399378
  • 829
  • 2
  • 10
  • 23
21
votes
8 answers

How do I recycle an IIS AppPool with Powershell?

I haven't really done any Windows scripting at all, so I am at a loss on how to pull this one off. Anyway, basically what we want to do is have a script that will take an argument on which IIS AppPool to recycle. I have done some research on…
Frew Schmidt
  • 9,364
  • 16
  • 64
  • 86
21
votes
5 answers

Is there a SCP alternative for PowerShell?

I need to write a script that transfers files from a folder onto another server (Linux), but the script that's transferring files is on windows, and I was wondering if there was an alternative to scp for PowerShell (or if there was another way of…
Saad
  • 26,316
  • 15
  • 48
  • 69
21
votes
4 answers

PowerShell functions that return true/false

I am pretty new with using PowerShell and was wondering if anyone would have any input on trying to get PowerShell functions to return values. I want to create some function that will return a value: Function Something { # Do a PowerShell cmd…
scapegoat17
  • 5,509
  • 14
  • 55
  • 90
21
votes
5 answers

Find files which does not contains selected string

I am trying to find all files, which does not contains a selected string. Find files which contains is easy: gci | select-string "something" but I do not have an idea how to negate this statement.
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
21
votes
7 answers

How to install .MSI using PowerShell

I am very new to PowerShell and have some difficulty with understanding. I want to install an .MSI inside PowerShell script. Can please explain me how to do that or provide me beginners level tutorial. $wiObject = New-Object -ComObject…
New Developer
  • 3,245
  • 10
  • 41
  • 78
21
votes
5 answers

Testing to see if a scheduled task exist in powershell

I can't figure out why the below code won't work: Function createFirefoxTask() { $schedule = new-object -com Schedule.Service $schedule.connect() $tasks = $schedule.getfolder("\").gettasks(0) foreach ($task in ($tasks | select Name))…
nullByteMe
  • 6,141
  • 13
  • 62
  • 99
21
votes
2 answers

Adding the file sizes of Get-ChildItem listing

My goal is to figure out how much space all images on my network drives are taking up. So my command to retrieve a list of all images is this: Get-ChildItem -recurse -include *jpg,*bmp,*png \\server01\folder Then I would like to just retrieve…
user2517266
  • 335
  • 1
  • 2
  • 6
21
votes
2 answers

Set-ItemProperty sets Registry Value as String on some systems instead of DWord, why?

I try to create an item using Set-ItemProperty in PowerShell, which works on most systems: New-PSDrive -name HKCR -PSProvider Registry -root HKEY_CLASSES_ROOT Set-ItemProperty -Path HKCR:\Software\MyCompany\ -Name Level -Value 5 -ErrorAction…
Erik
  • 2,316
  • 9
  • 36
  • 58
21
votes
3 answers

Read a Csv file with powershell and capture corresponding data

Using PowerShell I would like to capture user input, compare the input to data in a comma delimited CSV file and write corresponding data to a variable. Example: A user is prompted for a “Store_Number”, they enter "10". The input, “10” is then…
user2394966