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

MSOnline can't be imported on PowerShell (Connect-MsolService error)

I had this issue and couldn´t find any answer. The issue was that I was trying to use Azure cdmlets to connect to O365 via c# code, but I couldn´t get the connect-msolservice. ""The term is not recognized" error when you try to run administrative…
Danny Fallas
  • 628
  • 1
  • 5
  • 11
21
votes
2 answers

How to loop through files and rename using PowerShell?

I would like to rename all the jpg files in a folder to uniform convention like Picture00000001.jpg where 00000001 is a counter. It would be a walk in the park in C# but I would think this is the kind of bread and butter stuff that PowerShell was…
Ralph Shillington
  • 20,718
  • 23
  • 91
  • 154
21
votes
3 answers

Need help on Powershell Copy-Item from network drives

I am trying to use Copy-Item from remote machine to another remote machine with the command: Copy-Item -Path "\\machine1\abc\123\log 1.zip" -Destination "\\machine2\\c$\Logs\" I am constantly getting Error "Cannot find Path "\\machine1\abc\123\log…
Geeth
  • 321
  • 1
  • 2
  • 4
21
votes
5 answers

Create Outlook email draft using PowerShell

I'm creating a PowerShell script to automate a process at work. This process requires an email to be filled in and sent to someone else. The email will always roughly follow the same sort of template however it will probably never be the same…
Jason
  • 1,065
  • 1
  • 16
  • 26
21
votes
4 answers

Accessing Volume Shadow Copy (VSS) Snapshots from powershell

I am attempting to create and access a Volume Shadow Copy snapshot using the Windows Power Shell in Windows 7. I found that I can create snapshots using the following via a previous superuser question: (Get-WmiObject -list…
jordanm
  • 33,009
  • 7
  • 61
  • 76
21
votes
3 answers

Powershell 'Move-Item' doesn't make directory if it doesn't exists

I have a Powershell script which does a lot of things and one of them is moving files: $from = $path + '\' + $_.substring(8) $to = $quarantaine + '\' + $_.substring(8) Move-Item $from $to But it happens the directory structure isn't already…
Michiel
  • 7,855
  • 16
  • 61
  • 113
21
votes
5 answers

File Output in Powershell without Extension

Here is what I have so far: Get-ChildItem "C:\Folder" | Foreach-Object {$_.Name} > C:\Folder\File.txt When you open the output from above, File.txt, you see this: file1.txt file2.mpg file3.avi file4.txt How do I get the output so it drops the…
CaptHowdy
  • 239
  • 2
  • 3
  • 8
21
votes
3 answers

How to end a multi-line command in PowerShell

This should be easy, but can't figure it out. How do I end a multi-line command in PowerShell? For example if I enter Get-ChildItem | and press enter then I get a >> prompt which I assume is to continue the command. But if I then enter…
Svish
  • 152,914
  • 173
  • 462
  • 620
21
votes
3 answers

Powershell Get-ChildItem -Filter operates differently to Where clause with same value

I have a folder on a server called MyFolder. There are additional folders called MyFolder.1, MyFolder.2, MyFolder.3 etc. If I run: gci C:\Sample | ? { $_.Name -like "MyFolder.*" } I get the expected output: Directory: C:\Sample Mode …
Kieranties
  • 697
  • 1
  • 4
  • 14
21
votes
3 answers

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

I'm trying to move all the mails after removing the special characters in the filename to some destination based on the filename. FOLDLIST is an array, where I'm having the condition variable and destination foldername. Set-Location…
Tamilan
  • 951
  • 3
  • 11
  • 23
21
votes
8 answers

catching return code of a command with "invoke-command" - Powershell 2

I am using "invoke-command" to execute a script on a remote machine. invoke-command -computername -scriptblock {command to execute the script} My script returns "-1" when there are any errors. So, I wanted to ensure that script has…
Buddhika
21
votes
3 answers

Using ForEach with Get-ChildItem -recurse

I am trying to get a recursive list of files in a particular subfolder structure, then save them to a table so that I can use a foreach loop to work with each row. I have the following code: $table = get-childitem -recurse | where {!…
user1491315
21
votes
5 answers

Send files over PSSession

I just burned a couple of hours searching for a solution to send files over an active PSSession. And the result is nada, niente. I'm trying to invoke a command on a remote computer over an active session, which should copy something from a network…
kalbsschnitzel
  • 817
  • 1
  • 8
  • 29
21
votes
4 answers

How do I set up TFS PowerShell Snapin

I have installed TFS Power Tools and I am trying to use the powershell snapin, but I can't figure out how to set it up. When I look in the install folder, I only see the following 5…
TheSean
  • 4,516
  • 7
  • 40
  • 50
20
votes
5 answers

Test admin rights within PowerShell script?

Whats the best/easiest way to test for administrative rights in a PowerShell script? I need to write a script that requires administrative rights and want to know the best way to achieve it.
resolver101
  • 2,155
  • 11
  • 41
  • 53