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

What is the difference between Anaconda Prompt and Anaconda Powershell Prompt?

I am learning Python using Anaconda. Earlier I had only Anaconda Prompt. But after recent update of Anaconda through conda update conda I came to see Anaconda Powershell Prompt. Few commands I tried in new Powershell Prompt which I used to do…
RLD
  • 1,867
  • 3
  • 15
  • 20
22
votes
4 answers

Future of cmd & powershell

We were just today discussing it, so I went on a little search but found nothing, zip, nada. What is the future of ms's cmd shell? Do they intend to replace it completely with powershell in the future versions of windows, or just ship powershell as…
Rook
  • 60,248
  • 49
  • 165
  • 242
22
votes
3 answers

How to ignore escape sequences stored in PowerShell string variable?

In my PowerShell script, I'm running Select-String over a number of files, looking for a string passed into it via a variable ($id): foreach ($file in (ls "path\to\files")) { $found = $false $found = Select-String -Path $file $id -Quiet …
alastairs
  • 6,697
  • 8
  • 50
  • 64
22
votes
4 answers

Prevent integrated terminal from opening automatically

Whenever I open a PowerShell script in VS Code, the integrated terminal opens. How can we prevent the integrated terminal from opening automatically. I have searched the settings for "terminal" and have found nothing associated with auto-start.
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
22
votes
3 answers

powershell: how to evaluate a string

My file a.txt contains: delete from test_$suffix My PowerShell is: $a = get-content a.txt $suffix = "tableA" How would I manipulate $a to obtain the string delete from test_tableA ?
Daniel Wu
  • 5,853
  • 12
  • 42
  • 93
22
votes
5 answers

how to download and install git client for window using Powershell

I have to write automated powershell script for cloning repository from gihtub but I need to install git using command line.Could you please let me know how can I download and install git on window using command line without doing any manual…
Priya Rani
  • 1,063
  • 3
  • 11
  • 21
22
votes
1 answer

Bash/batch-like subshell in Powershell

In Unix shell, you can write this: ( cmd1 ; cmd2 ) | cmd3 In Windows Batch, you can write this ( cmd1 & cmd2 ) | cmd3 In both cases, the output of cmd1 and cmd2 is passed to cmd3 on stdin. Is it possible to do the same in Powershell? I haven't…
Kenn Humborg
  • 323
  • 2
  • 5
22
votes
2 answers

Copy current location to clipboard

How do I copy the current working directory to clipboard? PS C:\jacek> pwd | CLIP I get content like below. How can I copy only location/value without any whitespace or description? Path -- C:\jacek
Jacek
  • 11,661
  • 23
  • 69
  • 123
22
votes
4 answers

How to bring focus to window by process name?

If I'm understanding this correctly this code should capture the active window and keep it in focus. concentr.exe is the process name. How do I bring a window in focus based on process name? Add-Type @" using System; using…
user770022
  • 2,899
  • 19
  • 52
  • 79
22
votes
8 answers

Ctrl-C for quitting Python in Powershell now not working

Python fails to quit when using Ctrl-C in Powershell/Command Prompt, and instead gives out a "KeyboardInterrupt" string. Recently I've reinstalled Windows 10. Before the reinstall Ctrl-C quit python (3.5/2.7) fine, with no output. Does anyone know…
oblong
  • 625
  • 2
  • 6
  • 8
22
votes
9 answers

Listing processes by CPU usage percentage in powershell

How does one lists the processes using CPU > 1% by piping the output from Get-Process to Where-Object? Complete beginner to powershell all i can think is something like this Get-Process | Where-Object { CPU_Usage -gt 1% }
Ulug Toprak
  • 1,172
  • 1
  • 10
  • 21
22
votes
1 answer

Printing an array in Powershell

I am trying to print an array (I tried both with a for loop and directly with .ToString()), but I allways get a System.Object output. The content of the array is the result of this command: $singleOutput = Invoke-Command -ComputerName $server…
Alexander Meise
  • 1,328
  • 2
  • 15
  • 31
22
votes
1 answer

Force not working in non-interactive mode

Deleting folder 'C:\agent\_work\2\a\Foo\_PublishedWebsites\Foo\sourcejs' Remove-Item : Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available. At C:\agent\_work\2\s\Build\Deployment\PrepareWebsites.ps1:29…
Space Monkey
  • 981
  • 1
  • 9
  • 14
22
votes
7 answers

Cannot start service on computer '.'

I'm trying to create and start a windows service using PowerShell. The service is created but cannot be started when I use various names besides one particular name. When I create the service with the name of the exe file it can be started but when…
Itai Mo
  • 333
  • 1
  • 2
  • 7
22
votes
4 answers

Powershell run job at startup with admin rights using ScheduledJob

To ease some of my work I have created a powershell script which needs to : Run at startup. Run with admin rights as it has to write in c:\program files folder. I created the startup service using powershell like this : function…
Gagan93
  • 1,826
  • 2
  • 25
  • 38