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

Powershell: Filter the contents of a file by an array of strings

Riddle me this: I have a text file of data. I want to read it in, and only output lines that contain any string that is found in an array of search terms. If I were looking for just one string, I would do something like this: get-content afile |…
JMarsch
  • 21,484
  • 15
  • 77
  • 125
20
votes
1 answer

How to read CDATA in XML file with PowerShell?

I am having a difficult time reading an XML file with Cdata inside. in $xmlsource Test randomHTMLhere
]]>
powershell [xml]$xml =…
puttputt
  • 1,259
  • 2
  • 14
  • 25
20
votes
4 answers

Download .vhd image from Azure to local machine, and upload to another Azure account

I'd like to download a VM image to my local machine, so I can use it locally and upload it to another credential of Azure. I know that there is blob URL but wget didn't help to download it, because it…
Won
  • 1,795
  • 2
  • 12
  • 22
20
votes
5 answers

Powershell is removing comma from program argument

I want to pass in a comma separated list of values into a script as part of a single switch. Here is the program. param( [string]$foo ) Write-Host "[$foo]" Here is the usage example PS> .\inputTest.ps1 -foo one,two,three I would expect the…
StaticMethod
  • 593
  • 1
  • 7
  • 20
20
votes
1 answer

Powershell regex group replacing

I want to replace some text in every script file in folder, and I'm trying to use this PS code: $pattern = '(FROM [a-zA-Z0-9_.]{1,100})(?[a-zA-Z0-9_.]{1,7})' Get-ChildItem -Path 'D:\Scripts' -Recurse -Include *.sql |…
hmnzr
  • 1,390
  • 1
  • 15
  • 24
20
votes
4 answers

PowerShell folder permission error - Some or all identity references could not be translated

I am running this script as Admin and It does create the folders requred, just does not set the appropriate permissions. $Users = Get-Content "D:\New_Users.txt" ForEach ($user in $users) { $newPath = Join-Path "F:\Users" -childpath $user …
Siriss
  • 3,737
  • 4
  • 32
  • 65
20
votes
3 answers

How can I programmatically find a users HKEY_USERS registry key using powershell?

I wonder if there is a way to find a local user's registry key in HKEY_USERS if you know the login-name of that user on the local machine. I want to programmatically add stuff to a specific user's registry keys (Autorun for example), but I only know…
Erik
  • 2,316
  • 9
  • 36
  • 58
20
votes
7 answers

IIS7.5 PowerShell preloadEnabled

Is it possible I can use PowerShell command (e,g, New-WebSite) to create a web site and set site's preloadEnabled="true"?
hardywang
  • 4,864
  • 11
  • 65
  • 101
20
votes
3 answers

Passing empty arguments to executables using powershell

Powershell seems to drop empty string arguments when passed to a command. I have this code PS D:\> $b.name = "foo bar" PS D:\> ./echoargs $b.name Arg 0 is D:\echoargs.exe Arg 1 is foo bar PS D:\> $b.name = "" PS D:\> ./echoargs $b.name Arg 0 is…
user1353535
  • 651
  • 1
  • 5
  • 18
19
votes
1 answer

How to find files in directories with certain name using Get-ChildItem?

I have a project folder called topfolder and I want to find all files in all subfolders that match a certain pattern, e.g. when the folder contains foo anywhere in its name, I want to list all files inside it. I tried something like: gci .\topfolder…
Borek Bernard
  • 50,745
  • 59
  • 165
  • 240
19
votes
1 answer

How do I host a Powershell script or app so it's accessible via WSManConnectionInfo? (like Office 365)

The only ways I know to connect to a remote runspace include the following parameters WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "localhost", 80, "/Powershell",…
makerofthings7
  • 60,103
  • 53
  • 215
  • 448
19
votes
4 answers

Why would I use Powershell over C#?

I know that Powershell is quite powerful in that it is a scripting language in which you have access to the entire .Net framework (thats all I know about it). But i'm struggling to understand what's the big hype about Powershell when I could use C#…
Draco
  • 16,156
  • 23
  • 77
  • 92
19
votes
5 answers

Setting the start dir when calling Powershell from .NET?

I'm using the System.Management.Automation API to call PowerShell scripts a C# WPF app. In the following example, how would you change the start directory ($PWD) so it executes foo.ps1 from C:\scripts\ instead of the location of the .exe it was…
Richard Dingwall
  • 2,692
  • 1
  • 31
  • 32
19
votes
7 answers

Is it possible to create a Database in SQL Server with powershell?

I am trying to create a empty database in SQL server using powershell and SMO but cannot seem to find a way of doing it. Is this possible? Connection script for sql server: [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')…
ajack
  • 586
  • 1
  • 5
  • 13
19
votes
3 answers

Converting xml from UTF-16 to UTF-8 using PowerShell

What's the easiest way to convert XML from UTF16 to a UTF8 encoded file?
David Gardiner
  • 16,892
  • 20
  • 80
  • 117
1 2 3
99
100