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

How to check if an associative array is empty in powershell

$a = @() How do I check if $a above is empty (which it is). I would like to get $true as answer.
Spencer E
  • 203
  • 1
  • 2
  • 4
20
votes
3 answers

Why does Set-ItemProperty have no effect for IIS applications under Windows 10?

Most of our web applications include a Deploy.ps1 Powershell script. Octopus Deploy uses this to configure apps during production deployments, but we also use it to set up developers' local IIS settings. Works absolutely fine on Windows 7, Windows…
Dylan Beattie
  • 53,688
  • 35
  • 128
  • 197
20
votes
6 answers

Powershell File Compare

I am using a PowerShell script to move some files around on some servers. I want to test if a file I am going to move already exists in the destination. Not just a file with the same name. I thought Compare-Object $File1 $File2 Should do it but no…
zebidy
  • 215
  • 1
  • 2
  • 5
20
votes
3 answers

How to format SQLCMD output

I am using below command line to run a SQL query using SQLCMD sqlcmd -S Server -Q "select top 100 * From people" -d people -t 10 The table has 20 columns and when i look at output command line window wraps the text and makes it difficult to…
user1550159
  • 1,197
  • 3
  • 19
  • 36
20
votes
2 answers

Cross platform system libraries reference for PowerShell and Server Manager module

The program I am writing is using System.Management.Automation library to make use of PowerShell classes and interfaces that are defined there. There are two versions of those libraries: 1.0.0.0 and 3.0.0.0. Windows Server 2008 has in its GAC…
Mike
  • 842
  • 1
  • 9
  • 31
20
votes
3 answers

How open PowerShell as administrator from the run window

Is possible open a new PowerShell console as administrator through the run window, in Windows? I know that just typing 'powershell' in the run window is enough to start a new console, but is there a parameter to start it 'as…
mukade
  • 650
  • 1
  • 9
  • 11
20
votes
2 answers

What's the difference between `-Contains` and `-In` in PowerShell?

Other than the obvious reversal of the parameter order, what is the difference between the -Contains operator and PowerShell 3.0's new -In operator?
Jacob Krall
  • 28,341
  • 6
  • 66
  • 76
20
votes
4 answers

Nuget crash in visual studio 2015

Package manager console crash in visual studio 2015 enterprise just after start with error: Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the…
Maris
  • 4,608
  • 6
  • 39
  • 68
20
votes
5 answers

how to deploy windows phone 10 application to a device?

I am using a Nokia lumia630 device, which uses latest windows 10 insider preview build available. i created a sample windows UWP application and took a build of the same.The output of the build is an Appx. How can i install this Appx to my device?…
Joseph
  • 1,054
  • 1
  • 11
  • 25
20
votes
2 answers

Azure Powershell script to swap Azure App Service (website) deployment slots

I'm looking for a way to use Azure PowerShell commands to do a deployment swap for an Azure App Service (previously Azure Websites). All of the posts I've seen say to use the command Move-Deployment -ServiceName but that appears to only be valid…
Jeff Treuting
  • 13,910
  • 8
  • 36
  • 47
20
votes
2 answers

Invoke-SqlCmd doesn't return long string?

For the following code $sql = "select ..... for xml path('row')" # returns a long xml file $x = Invoke-SqlCmd -Server xxxx $sql $r = $x[0].ItemArray[0] The returned $r has a truncated xml string. How to make sure the full long string is returned?
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
20
votes
3 answers

String to DateTime conversion in PowerShell

I am trying to convert the time stamp value of a file to date time for comparing two date time differences. The data would be coming in format 24122014_022257. I need to convert this into date time so that I can compare the…
Renji
  • 391
  • 2
  • 7
  • 20
20
votes
4 answers

Copying to the clipboard in PowerShell without a new line

Is there a way to remove a new line from out-clipboard or clip in PowerShell? I'm using this code to copy current path to clipboard: function cl() { (Get-Location).ToString() | clip } And every time I use this, a new line is added to the copied…
IGRACH
  • 3,506
  • 6
  • 33
  • 48
20
votes
2 answers

Jenkins: Access global passwords in powershell

I am having trouble accessing the jenkins global password as an environment variable in powershell. I have done the following. Not sure what else I am missing. Installed Credentials Binding Plugin, Environment Injector Plugin, Mask Passwords…
user4296485
  • 201
  • 1
  • 2
  • 3
20
votes
3 answers

How to use Extension methods in Powershell?

I have the following code: using System; public static class IntEx { /// /// Yields a power of the given number /// /// The base number /// the power to be…
Ivan Prodanov
  • 34,634
  • 78
  • 176
  • 248