PowerShell Cookbook

This is a list of items my colleagues and I have found useful in our work. It’s not intended to be encyclopedic, but rather a place to record things a beginner would find useful, especially things that might take a long time to figure out.

This page was started before O’Reilly published Windows PowerShell Cookbook by Lee Holmes. I recommend O’Reilly’s book, but this page is unrelated to it.

See also PowerShell gotchas.

PowerShell logo

Outline

 

Getting started/installation


Install PowerShell

You can obtain PowerShell from:
https://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx

top


Install Community Extensions library

The PowerShell Community Extensions (PSCX) library is available here:
https://www.codeplex.com/Wiki/View.aspx?ProjectName=PowerShellCX

This is a useful collection of cmdlets and functions. It installs a “PowerShell Here” context menu in WindowsExplorer that opens a PowerShell command window in the folder that you right-click on. Also, PSCX provides a sample Profile.ps1 file.

Once PSCX is installed, type man about_pscx to see an overview of the cmdlets, providers, etc. that come with PSCX.

top


Get rid of the “execution of scripts is disabled” message

The first problem you are likely to encounter when running PowerShell scripts is something like this:

PSH> .\myScript.ps1

File D:\myScript.ps1 cannot be loaded. The file
D:\myScript.ps1 is not digitally signed. The script will not execute on the
system. Please see "get-help about_signing" for more details..
At line:1 char:13 + .\myScript.ps1 <<<<

This is due the to the default security setting in PowerShell that prohibits malicious scripts from running.

You can alter this behavior by doing this:

PSH> set-executionPolicy RemoteSigned

Now only scripts coming from remote sources will require digital signing.

top


Set up your “scripts:” PowerShell drive location

Once you’ve written a number of PowerShell scripts, you might find it useful to collect them in one place and create a PSDrive named scripts: to find them quickly. You could add the following to your PSCX profile to create such a PSDrive.

New-PSdrive -name scripts -PSprovider filesystem -root C:\bin\PowerShellScripts

top


Configure your command prompt

To configure your command prompt, simply create a function named prompt and put it in your profile. For example, the following will cause the working directory to be displayed.

function prompt { "$pwd> " }

Note that you could put any code you want inside the prompt function and that code will run every time you hit return.

top


Miscellaneous tasks


Write to the screen

Use Write-Host to write output. You can optionally specify -foregroundcolor to color the output. For example, errors and warnings may be highlighted in red.

Example:

Write-Host "Hello world" -foregroundcolor red

top


Prompt user for input

Use Read-Host.

Example:

$a = Read-Host "Enter your name"
Write-Host "Hello" $a

top


Manipulate dates

The cmdlet get-date returns a DateTime object. With no argument, it returns the current time and date. With a string argument, no need to quote, it parses the string into a date.

Example: Find the number of days and hours since the US bicentennial.

(get-date) - (get-date 7/4/1976)

You can also cast strings to DateTime object by using the cast [datetime].

top


Send email

Use the Send-SmtpMail cmdlet from PowerShell Community Extensions.

Example:

Send-SmtpMail -SmtpHost wotan.mdacc.tmc.edu -from cook@mdanderson.org -to cook@mdanderson.org -body "hello world"

top


Sleep

Use the Start-Sleep cmdlet. Takes seconds by default, but has a -milliseconds option.

Example:

Write-Host "hello"; Start-Sleep 5; Write-Host "world"

top


List a directory (recursively)

You can use the dir command, which is really an alias to Get-ChildItem. To list a directory recursively, just add the -recurse option.

Example:

dir f:\bin -recurse

top


Test whether a file exists

Use test-path.

top


Read file lines into an array

Use get-content.

Example:

$a = (get-content foo.txt)

top


Write to a file

Use Out-File. Unless you want Unicode output, specify -encoding ASCII

Example:

$foo | out-file -encoding ASCII foo.txt

top


Rename a file

Use Rename-Item or its alias ren.

top


Delete a file

Use Delete-Item or its alias del.

top


Work with regular expressions

See Regular expressions in PowerShell and Perl.

top


Split and join strings

Strings have a split method. The argument to split() is a string containing characters to split on. The function [regex]::split is more general. Its first argument is the string to split, and its second argument is a regular expression on which to split.

Example:

$a.split("`t ")

will break the string $a into an array of strings, splitting wherever there is a tab or a space.

Example:

$a = "123,456,apple"; [regex]::split($a, ",(?!\d)")

will split $a on commas not followed by digits. So the split would return “123,456” and “apple”.

If the string you’re splitting is a Windows path, you may want to use the specialized Split-Path command.

To join an array into a single string, use the [string]::join method. The first argument is the separation character and the second is the array.

Example:

$a = 1, 2, 3;
#note: this is an array, not a string
$b = [string]::join("*", $a)

Now $b contains “1*2*3”.

top


Grab a web page

Use the either Get-Url from PSCX or the net.webclient object from .NET. The former is more succinct but the latter allows more options.

Example:

$w = Get-Url "https://www.w3.org"

$w = (new-object net.webclient).DownloadString("https://www.w3.org")

The code (new-object net.webclient) creates a .NET WebClient object with many useful methods. For example, you could call DownladFile to save directly to disk rather than to a string. There are also UploadData and UploadFile methods.

top


Read and write to registry

You can navigate the registry as you would the file system, though there are some details to know.

Each hive of the registry is like a drive. So, for example, to explore HKEY_CURRENT_USER, you can cd HKCU: and then use cd to work your way down the tree. Use Get-ItemProperty to read and Set-ItemProperty to write. You can also use Remove-ItemProperty to delete.

Example:

The commands below will list the contents of the registry node that configures the cmd.exe shell. By setting CompletionChar to 9, we turn on tab completion.

cd HKCU:\Software\Microsoft\Command Processor
Get-ItemProperty .
Set-ItemProperty . -name CompletionChar -Value 9

This TechNet article goes into more details.

top


Understand quotes

PowerShell has four kinds of quotes: single and double ordinary quotes, and single and double here-strings. Inside double quotes and double here-strings, variable names are replaced with their values and PowerShell escape sequences are interpreted. In single quotes and single here-strings, variable names are not expanded and escape sequences are not interpreted. For example, the code snippet

    $a = "bar"
    'foo`t$a', "foo`t$a"

will produce the output

    foo`t$a
    foo    bar

because inside the double quote, `t expands to a tab and $a expands to “bar”.

PowerShell here-strings are like here-documents in Perl. Inside a here-string, double and single quotes are not special but quoted literally. Also, line breaks are preserved.

A here-string begins with either @" or @' and ends with the same symbols in the opposite order. There must be a newline following the opening marker and before the closing marker.

Example

    $a = "bar"
    $b = @"
    foo "baz"
    'qux' $a
    "@
    $b

produces

    foo "baz"
    'qux' bar

and

    $a = "bar"
    $b = @'
    foo "baz"
    'qux' $a
    '@
    $b

produces

    foo "baz"
    'qux' $a

Note that there must be no white space following the quote opening a here-string. Otherwise you will get the message “Unrecognized token in source text.”

Although they look similar, PowerShell here-strings and C# verbatim strings are fairly different. The following table summarizes the differences.

C# verbatim strings PowerShell here-strings
May contain line breaks Must contain line breaks
Only double quote variety Single and double quote varieties
Begins with @” Begins with @” (or @’) plus a line break
Ends with “ Ends with a line break followed by “@ (or ‘@)
Cannot contain un-escaped double quotes May contain quotes
Turns off C# escape sequences ‘@ turns off PowerShell escape sequences but “@ does not

top


Time a command

Use Measure-Command to time how long a task takes to complete.

top


Text to speech

Use Out-Speech from PSCX.

top


Access the Windows clipboard

Use the PSCX cmdlets Get-Clipboard and Out-Clipboard to read from and write to the clipboard.

top


Load a .NET assembly

You can call LoadWithPartialName. For example, to load the assembly for the Team Foundation Server API, you would execute

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")

See also Resolve-Assembly from PSCX.

top


Execute code created at run time

The command Invoke-Expression is analogous to eval in Perl or JavaScript. Invoke-Expression $str executes the code contained in the string $str.

top


Execute a program with a space in its path

Put quotation marks around the path and stick an ampersand in front. For example,

& "C:\Program Files\WinEdt Team\WinEdt\WinEdt.exe"

will launch the executable WinEdt.exe which has two spaces in its full path.

Note that you cannot leave out the ampersand. Unlike cmd.exe, PowerShell does not assume all strings are commands. Without the ampersand, a quoted path is just a string.

top


More PowerShell resources

PowerShell introduction
PowerShell Day 1 booklet
PowerShell gotchas
Regular expressions in PowerShell and Perl