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

Add Column to CSV Windows PowerShell

I have a fairly standard csv file with headers I want to add a new column & set all the rows to the same data. Original: column1, column2 1,b 2,c 3,5 After column1, column2, column3 1,b, setvalue 2,c, setvalue 3,5, setvalue I can't find anything…
Paul
  • 431
  • 2
  • 10
  • 24
22
votes
1 answer

Can I send some text to the STDIN of an active process under Windows?

I searched the web for that question and landed on Server Fault: Can I send some text to the STDIN of an active process running in a screen session? Seems like it is ridiculously easy to achieve this under Linux. But I need it for a Win32 Command…
eckes
  • 64,417
  • 29
  • 168
  • 201
22
votes
3 answers

I need help understanding PowerShell security and file access issues

I'm working with PowerShell, running a script (from my console) that includes this line: $inpath = "C:\users\xxxxx\path\foo\bar" and I keep getting this error: Get-Content : Access to the path 'C:\users\xxxxx\path\foo\bar' is denied. At…
dwwilson66
  • 6,806
  • 27
  • 72
  • 117
22
votes
3 answers

PowerShell history: how do you prevent duplicate commands?

Background: PowerShell history is a lot more useful to me now that I have a way to save history across sessions. # Run this every time right before you exit PowerShell get-history -Count $MaximumHistoryCount | export-clixml $IniFileCmdHistory; Now,…
dreftymac
  • 31,404
  • 26
  • 119
  • 182
22
votes
3 answers

How to list the files in a zip in powershell?

I am new to powershell and looking to list all the files, contained in zip files in a directory. I don't want to use any third-party tool. Structure of the directory is mydir > dir a.zip b.zip c.zip with each file containing files named 1.txt or…
user487257
  • 1,071
  • 2
  • 9
  • 16
22
votes
5 answers

start-Transcript not capturing all output to log file..?

I have the below code that goes through and gets scheduled tasks info and puts the output that occurs on the screen to a log file. However, what I have noticed is that all errors are logged EXCEPT for servers that have "Access is denied" - how can…
lara400
  • 4,646
  • 13
  • 46
  • 66
22
votes
4 answers

Handle errors in ScriptBlock in Invoke-Command Cmdlet

I am trying to install a service on a remote machine using the powershell. So far I have the following: Invoke-Command -ComputerName $remoteComputerName -ScriptBlock { param($password=$password,$username=$username) $secpasswd =…
flayn
  • 5,272
  • 4
  • 48
  • 69
22
votes
4 answers

How can I grep for a text pattern in a zipped text file?

Our daily feed file averages 2 GB in size. These files get archived to a single zip file at the end of each month and stored in a network share. From time to time, I have a need to search for certain records in those files. I do this by connecting…
dawntrader
  • 765
  • 2
  • 11
  • 19
22
votes
1 answer

Display the name of the currently executing function

How can I retrieve the name of the function that is currently running in powershell? Here is an example of what I want: Function write-FunctionName { write-host "The name of this function is: *SomethingGoesHereButWhat?*" } Then when I execute it,…
Winfred
  • 940
  • 1
  • 8
  • 23
22
votes
4 answers

How to schedule a task wether the user is logged on or not in PowerShell?

I have a problem regarding how to make a scheduled task to run whether the user is logged on or not. It must be done in PowerShell. What I have done is: $WINDIR/system32/schtasks.exe /create /tn TaskName /sc daily /st 15:05:00 /tr…
Diemauerdk
  • 5,238
  • 9
  • 40
  • 56
22
votes
2 answers

Hardcode password into powershells "New-PSSession"

I have a script to get and set user's Windows environment variables on other computers for a given user. Is it possible to hard code the password for this user so that I don't have to type it every time I run the script? My script looks something…
user952342
  • 2,602
  • 7
  • 34
  • 54
21
votes
5 answers

PowerShell is slow (much slower than Python) in large Search/Replace operation?

I have 265 CSV files with over 4 million total records (lines), and need to do a search and replace in all the CSV files. I have a snippet of my PowerShell code below that does this, but it takes 17 minutes to perform the action: ForEach ($file in…
Keith
  • 1,959
  • 10
  • 35
  • 46
21
votes
5 answers

Powershell Execute remote exe with command line arguments on remote computer

I've searched all over and tried different variations of commands, but I am still not there yet. My goal is to run an exe that already resides on a remote machine and pass in command line arguments. I've tried invoke-command, but I can't seem to…
gregs
  • 605
  • 2
  • 7
  • 16
21
votes
5 answers

Quoting -replace & variables

This is in response to my previous question: PowerShell: -replace, regex and ($) dollar sign woes My question is: why do these 2 lines of code have different output: 'abc' -replace 'a(\w)', '$1' 'abc' -replace 'a(\w)', "$1" AND according to the 2…
Vippy
  • 1,356
  • 3
  • 20
  • 30
21
votes
2 answers

PowerShell equivalent of the C# "is" operator?

In a PowerShell script, I need to determine whether a .NET method call is actually returning the correct type of object, or at least a compatible type. How can I do this?
Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86