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

Powershell can speak, but can it write if i speak?

Following is the way to make powershell to speak. Add-Type -AssemblyName System.Speech $synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer $synthesizer.Speak('Hey, I can speak!') Actually i would like to do opposite.…
Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230
20
votes
6 answers

Calling powershell cmdlets from Windows batch file

Ok something so simple is just not working for me. I got a cmdlet that accepts a single parameter. I am trying to call a cmdlet within a Windows batch file. The batch file contains: cd %SystemRoot%\system32\WindowsPowerShell\v1.0 powershell…
Th3Fix3r
20
votes
2 answers

Powershell: How do I get the exit code returned from a process run inside a PsJob?

I have the following job in powershell: $job = start-job { ... c:\utils\MyToolReturningSomeExitCode.cmd } -ArgumentList $JobFile How do I access the exit code returned by c:\utils\MyToolReturningSomeExitCode.cmd ? I have tried several options,…
mark
  • 59,016
  • 79
  • 296
  • 580
20
votes
3 answers

Change path separator in Windows PowerShell

Is it possible to get PowerShell to always output / instead of \? For example, I'd like the output of get-location to be C:/Documents and Settings/Administrator. Update Thanks for the examples of using replace, but I was hoping for this to happen…
ctuffli
  • 3,559
  • 4
  • 31
  • 43
20
votes
1 answer

Powershell - Find the user who invoked the script

I have a script(Let's call it myPSScript.ps1) which takes two parameters and performs predefined steps. Script is located in a Windows Server box which people login and execute the script. Supports two users to be logged in at the given time. I want…
Sanjeev
  • 673
  • 4
  • 10
  • 19
20
votes
7 answers

Start-process raises an error when providing Credentials - possible bug

Would you possibly know why this error is being raised in response to the code below. User-name and password have been verified as correct. $secPassword = ConvertTo-SecureString "Password" -AsPlaintext -Force $farmCredential = New-Object…
chris
  • 233
  • 2
  • 3
  • 6
20
votes
3 answers

PowerShell pass by reference not working for me

I'm trying to make a simple swap function in PowerShell, but passing by reference doesn't seem to work for me. function swap ([ref]$object1, [ref]$object2){ $tmp = $object1.value $object1.value = $object2.value $object2.value = $tmp } $a =…
Ed Manet
  • 3,118
  • 3
  • 20
  • 23
20
votes
4 answers

How to check if a port is in use using powershell

Is there a way in powershell to check if a given port is in use or not?
Jeevan
  • 8,532
  • 14
  • 49
  • 67
20
votes
4 answers

Powershell: Unable to update PowerShellGet , error: The version '1.4.7' of module 'PackageManagement' is currently in use

Win10 laptop, in service for a couple years. I have been stuck on this for a couple of days. I try this command: Install-Module –Name PowerShellGet –Force -AllowClobber Which throws this error: WARNING: The version '1.4.7' of module…
Jonesome Reinstate Monica
  • 6,618
  • 11
  • 65
  • 112
20
votes
3 answers

how to execute sql script using azure devops pipeline

I have SQL script which I want to execute using azure DevOps pipeline I found multiple tasks for SQL but can not find any required task where I can pass sql server , database name and login details. Is there any task available for this ? If there is…
megha
  • 621
  • 2
  • 11
  • 36
20
votes
1 answer

PowerShell error when converting a SecureString back to plain text

How do I convert a SecureString back to plain text? From Example 4 of the Microsoft Documentation. $secureString = ConvertTo-SecureString -String 'Example' -AsPlainText $secureString # 'System.Security.SecureString' ConvertFrom-SecureString…
Arik
  • 205
  • 3
  • 8
20
votes
2 answers

Temporarily change powershell language to English?

I wrote some software that uses the output of system (powershell) commands, but did not foresee that the output would be different for languages other than English. Is there a way to temporarily change the language in Powershell to English for just…
stevec
  • 41,291
  • 27
  • 223
  • 311
20
votes
8 answers

in C#/Powershell - Is it possible to change the Idle TimeOut for an IIS Application Pool?

I want to disable the idle timeout (Set it to Zero) of an application pool and I want to perform this at setup time, is it possible to perform this action from C# or PowerShell?
Bongo Sharp
  • 9,450
  • 8
  • 25
  • 35
20
votes
11 answers

NetBIOS domain of computer in PowerShell

How can I get the NetBIOS (aka 'short') domain name of the current computer from PowerShell? $ENV:USERDOMAIN displays the domain of the current user, but I want the domain that the current machine is a member of. I've discovered you can do it pretty…
David Gardiner
  • 16,892
  • 20
  • 80
  • 117
20
votes
7 answers

Service Principal az cli login failing - NO subscriptions found

Trying to perform an az cli login using a Service Principal and it is throwing an error stating No subscriptions found for . If this is expected, use '--allow-no-subscriptions'. This code has worked fine previously but now…
phydeauxman
  • 1,432
  • 3
  • 26
  • 48