PowerShell Reference Card
PowerShell Reference Card
com
tech facts at your fingertips
CONTENTS INCLUDE:
Windows PowerShell
n
About Windows Powershell
n
The Language
n
Operators
n
Basic Tasks—Text and Files
n
Types and Objects
n
Building Custom Objects By Bruce Payette
n
Hot Tips and more...
Windows what the UNIX shells do for UNIX: provide a powerful, Ctrl-Left Arrow, Move the editing cursor left and right a word at a time.
Ctrl-Right Arrow
well-integrated command-line experience for the operation
Home Move the editing cursor to the beginning of the current
system. Unfortunately since Windows is mostly managed through command line.
objects (WMI, COM and .NET) this required creating a new kind End Move the editing cursor to the end of the current command line.
of shell. So why create it now? As Windows moves off the desktop Up/Down Arrows Move up and down through the command history.
and into server farms or application servers like print, DNS Insert Key Toggles between character insert and character overwrite modes.
and LDAP services, command-line automation becomes a Delete Key Deletes the character under the cursor
fundamental requirement. Backspace Key Deletes the character behind the cursor.
This refcard covers starting and using Windows PowerShell, F7 Pops up command history in a window on the console. Use
the up and down arrows to select a command then Enter to
including the syntax for all statements, operators and other execute that command.
elements of the language. Also included are examples of how Tab Does command line completion. PowerShell completes on
filenames, cmdlet names (after the dash), cmdlet parameter
to use .NET, COM, ADSI and WMI objects from PowerShell.
names and property and method names on variables.
Finally, it includes tips and tricks— short examples showing
how to perform common tasks from PowerShell.
The Language
www.dzone.com
Getting Started with PowerShell PowerShell parses text in one of two modes—command mode,
where quotes are not required around a string and expression
PowerShell is freely available through the Microsoft Windows mode where strings must be quoted. The parsing mode is
determined by what’s at the beginning of the statement. If it’s a
Update Service packaged as an optional update for Windows
command, then the statement is parsed in command mode. If
XP SP2, Windows Vista and Windows Server 2003. It is also
it’s not a command then the statement is parsed in expression
included with Windows Server 2008 as an optional component.
mode as shown:
Once installed, it can be started from the Start menu or simply
PS (1) > echo 2+2 Hi there # command mode – starts with
by running “powershell.exe”. Basic things you need to know: ‘echo’ command
n Use the “exit” keyword to exit the shell 2+2 Hi there
PS (2) > 2+2; “Hi there” # expression mode starts with 2
n Ctrl-C will interrupt the current task returning you to the prompt 4
Hi there
n A command can be spread over multiple lines and the PS (3) > echo (2+2) Hi (echo there) # Mixing and matching
modes with brackets)
interpreter will prompt for additional input. The line continuation
4 Hi there
character is the back-quote ‘`’ (also called the back-tick).
n To get help about a command you can do “help command”.
Get More Refcardz
Windows PowerShell
and Double precisions and Decimal. Banker’s rounding is used PS (3) > $h[“thedate”]
when rounding values. Expressions are widened as needed. A
unique feature in PowerShell are the multiplyer suffixes which Tuesday, October 24, 2006 9:46:13 PM
make it convenient to enter larger values easily: PS (4) > $h.thedate
Multiplier Multiplication Example Equivalent .NET Type Tuesday, October 24, 2006 9:46:13 PM
Suffix Factor Value @{ a=1; b=2}
kb or KB 1024 1KB 1024 System.Int32 Types
[typename]
mb or MB 1024*1024 2.2mb 2306867.2 System.Double
gb or GB 1024*1024*1024 1Gb 1073741824 System.Int32 Type Conversions: For the most part, traditional shells only deal
with strings. Individual tools would have to interpret (parse) these
Strings: PowerShell uses .NET strings. Single and Double strings themselves. In PowerShell, we have a much richer set of
quoted strings are supported. Variable substitution and escape objects to work with. However, we still wanted to preserve the
sequence processing is done in double-quoted strings but not ease of use that strings provide. We do this through the Power-
in single quoted ones as shown: Shell type conversion subsystem. This facility will automatically
PS (1) > $x=”Hi” convert object types on demand in a transparent way. The type
PS (2) > “$x bob`nHow are you?” converter is careful to try and not lose information when doing a
Hi bob
How are you? conversion. It will also only do one conversion step at a time. The
PS (3) > ‘$x bob`nHow are you?’ user may also specify explicit conversions and, in fact, compose
$x bob`nHow are you?
those conversions. Conversions are typically applied to values but
The escape character is backtick instead of backslash so that they may also be attached to variables in which case anything
file paths can be written with either forward slash or backslash. assigned to that variable will be automatically be converted.
foreach Cmdlet: This cmdlet can be used to iterate over Operator Example Equivalent Description
collections of operators (similar to the map( ) operation found = $a= 3 Sets the variable to the specified
in many other languages like Perl.) There is a short alias for this $a,$b,$c =1,2,3 value. Multiple assignment is
supported.
command ‘%’. Note that the $_ variable is used to access the
+= $a += 2 $a = $a + 2 Performs the addition operation
current pipeline object in the foreach and where cmdlets.
in the existing value then assign
1..10 | foreach { $_ * $_ } the result back to the variable.
$t = 0; dir | foreach { $t += $_ } ; $t
1..10 | %{ “*” * $_ } -= $a -= 13 $a = $a – 13 Performs the subtraction
operation in the existing value
where Cmdlet: This cmdlet selects a subset of objects from a then assign the result back to the
stream based on the evaluation of a condition. The short alias variable.
switch Statement: The PowerShell switch statement combines /= $a /= 3 $a = $a / 3 Divides the value of a variable by
the specified value
both branching and looping. It can be used to process collections
%= $a %= 3 $a = $a % 3 Divides the value of a variable by
of objects in the condition part of the statement or it can be used the specified value and assigns the
to scan files using the –file option. remainder (modulus) to the variable
Comparison Operators: Most of the PowerShell operators are Metacharacter Description Example
the same as are usually found in C-derived languages. The Matches any “word” character,
comparison operators, however, are not. To allow the ‘>’ and ‘<’ \w approximately equivalent to “abcd defg” -match “\w+”
[a-zA-Z0-9]
operators to be used for redirection, a different set of characters
\W Matches any non-word character “abcd defg” -match “\W+”
had to be chosen so PowerShell operators match those found in
\s Matches any whitespace character “abcd defg” -match “\s+”
the Bourne shell style shell languages. (Note: when applying
a PowerShell operator against collection, the elements of the Matches any non-whitespace
\S “abcd defg” -match “\s+”
character.
collection that compare appropriately will be returned instead
Matches any digit or non-digit
of a simple Boolean.) \d \D
respectively
12345 -match “\d+”
Pattern Matching Operators: PowerShell supports two sets of Parameter with initializer expression; name Additional parameter specifications
pattern-matching operators. The first set uses regular expressions followed by = symbol, followed by an expression are separated by commas
In general, the easiest way to get things done in PowerShell but can also use them to list the defined variables by doing
is with cmdlets. Basic file operations are carried out with the dir variables:
“core” cmdlets. These cmdlets work on any namespace. This or remove a function called “junk” by doing:
means that you can use them to manipulate files and directories del function:/junk
New-Item ni Create a new empty file or directory. The type of object is controlled by the -type parameter.
Mkdir md mkdir Mkdir is implemented as a function in PowerShell so that users can create directories without having to
specify –type directory
Get-Content gc type cat Send the contents of a file to the output stream.
Set-Content sc Set the contents of a file. UNIX and cmd.exe have no equivalent. Redirection is used instead. The difference
between Set-Content and Out-File is discussed in detail in Chapter 10 of Windows PowerShell in Action.
I/O Redirection
Operator Example Results Description
> dir > out.txt Contents of out.txt are replaced. Redirect pipeline output to a file, overwriting the current contents
>> dir >> out.txt Contents of out.txt are appended to. Redirect pipeline output to a file, appending to the existing content.
2> dir nosuchfile.txt 2> err.txt Contents of err.txt are replaced by the error messages Redirect error output to a file, overwriting the current contents
2>> dir nosuchfile.txt 2>> err.txt Contents of err.txt are appended with the error messages Redirect error output to a file, overwriting the current contents
2>&1 dir nosuchfile.txt 2>&1 The error message is written to the output. The error messages are written to the output pipe instead of the error pipe.
Searching Through Text: The fastest way to search through text and files is to use the select-string cmdlet as shown:
select-string Username *.txt –case # case-sensitive search for Username
dir –rec –filter *.txt | select-string # case-insensitive search
# through a set of files
dir –rec –filter *.cs |
select-string –list Main # only list the first match
Formatting and Output: by default the output of any expression Output is also handled by a set of cmdlets that send the
that isn’t redirected will be displayed by PowerShell. The default output to different locations.
display mode can be overridden using the formatting cmdlets:
Cmdlet Description Example
Cmdlet Description Example Out-File Writes formatted text to a file dir | out-file –encoding
unicode foo.txt
Format-Table Formats a set of properties dir | format-table name, length
into a table Out-Host Writes formatted text to the screen dir | out-host -pag
Format-List Displays properties 1 per line dir | format-list * Out-Null Discards all output (equivalent to > dir | out-null
in a list. $null)
Format-Wide Displays a single property in dir | format-wide Out-Printer Sends formatted output to the printer. cat report.ps | out-printer
multiple columns
Out-String Formats input as strings and writes them dir | out-string | where {$_.
Format-Custom Complex formatter dir | format-custom to the output pipe match “x”}
Static methods are invoked using the ‘::’ operator with an expres-
Type Alias Corresponding .NET Type Example
sion that evaluates to a type on the left-hand side and a member on
[int] System.Int32 1 -15 1kb 0x55aa -15
the right hand side
[long] System.Int64 10000000000
[math]::sqrt(33)
[string] System.String “Hello`nthere” ‘hi’ $m = [math]
[char] System.Char [char] 0x20 $m::pow(2,8)
Along with .NET, PowerShell also lets you work with COM object. The other major object model used in PowerShell is WMI—
This is most commonly used as the Windows automation mecha- Windows Management Infrastructure. This is Microsoft’s imple-
nism. The following example shows how the Microsoft Word mentation of the Common Instrumentation Model or CIM. CIM
automation model can be used from PowerShell: is an industry standard created by Microsoft, HP, IBM and many
Listing: Get-Spelling Script — this script uses Word to spell other computer companies with the intent of coming up with a
check a document common set of management abstractions. WMI is accessed in
if ($args.count -gt 0) PowerShell through the Get-WMIObject cmdlet and through
{ #1 the [WMI] [WMISearcher] type accelerators. For example, to get
@”
information about the BIOS on your computer, you could do:
Usage for Get-Spelling:
PS (1) > (Get-WmiObject win32_bios).Name
Copy some text into the clipboard, then run this script. It will v3.20
display the Word spellcheck tool that will let you correct the
spelling on the text you’ve selected. When you’re done it will
ADSI (active directory)
put the text back into the clipboard so you can paste back into
the original document.
Support for active directory is accomplished through type
“@ accelerators. A string can be cast into an ADSI (LDAP) query
exit 0
} and then used to manipulate the directory as shown:
$domain = [ADSI] `
$shell = new-object -com wscript.shell
$word = new-object -com word.application >> “LDAP://localhost:389/dc=NA,dc=fabrikam,dc=com”
$word.Visible = $false PS (2) > $newOU = $domain.Create(“OrganizationalUnit”,
“ou=HR”)
$doc = $word.Documents.Add() PS (3) > $newOU.SetInfo()
$word.Selection.Paste() PS (5) > $ou = [ADSI] `
>> “LDAP://localhost:389/
if ($word.ActiveDocument.SpellingErrors.Count -gt 0) ou=HR,dc=NA,dc=fabrikam,dc=com”
{ >>
$word.ActiveDocument.CheckSpelling() PS (7) > $newUser.Put(“title”, “HR Consultant”)
$word.Visible = $false PS (8) > $newUser.Put(“employeeID”, 1)
$word.Selection.WholeStory()
PS (9) > $newUser.Put(“description”, “Dog”)
$word.Selection.Copy()
PS (10) > $newUser.SetInfo()
$shell.PopUp( “The spell check is complete, “ +
PS (12) > $user = [ADSI] (“LDAP://localhost:389/” +
“the clipboard holds the corrected text.” )
} >> “cn=Dogbert,ou=HR,dc=NA,dc=fabrikam,dc=com”)
else >>
{
[void] $shell.Popup(“No Spelling Errors were detect-
ed.”) Building Custom Objects in PowerShell
}
PowerShell has no language support for creating new types.
$x = [ref] 0
$word.ActiveDocument.Close($x) Instead this is done through a series of commands that allow
$word.Quit() you to add members (properties, fields and methods) to existing
object. Here’s an example:
DZone, Inc.
ISBN-13: 978-1-934238-01-1
1251 NW Maynard
ISBN-10: 1-934238-01-5
Cary, NC 27513
50795
888.678.0399
The DZone Network is a group of free online services that aim to 919.678.0300
satisfy the information needs of software developers and architects. Refcardz Feedback Welcome
From news, blogs, tutorials, source code and more, DZone offers
$7.95
refcardz@dzone.com
everything technology professionals need to succeed. Sponsorship Opportunities 9 781934 238011
To quote PC magazine, “DZone is a developer’s dream.” sales@dzone.com
Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, Version 1.0
mechanical, photocopying, or otherwise, without prior written permission of the publisher.