You are on page 1of 3

Windows PowerShell Quick Reference Windows PowerShell Quick Reference

How to Access Arguments How to Solicit Input How to Read a Text File How to Write Conditional Statements
To access command-line arguments used when starting To solicit input from a user, use the Read-Host cmdlet, To read the contents of a text file into a variable, call the To write an If statement use code similar to this:
a script use the automatic variable $args. You can cycle followed by the prompt to be displayed: Get-Content cmdlet followed by the path to the text file:
through the individual arguments in the $args collection $a = "white"
by using code similar to this: $a = Read-Host "Please enter your name" $a = Get-Content C:\Scripts\Test.txt if ($a -eq "red")
{"The color is red."}
foreach ($i in $args) {$i} Each line in the file ends up as an item in the array $a. If elseif ($a -eq "white")
you want to access a single line in the file you can simply {"The color is white."}
To access a particular argument use the collection index How to Insert Line Breaks specify the index number corresponding to that line: else
number, with 0 representing the first item in the To insert a line break into a Windows PowerShell script {"The color is blue."}
collection, 1 representing the second item, etc: use the backtick (`) : $a[0]
Instead of writing a series of If statements you can use a
$args{0] Write-Host ` This command echoes back the last line in $a: Switch statement, which is equivalent to VBScript’s
"This is a continuation of the line." Select Case statement:
You can reference the last item in a collection by using $a[-1]
the index number –1: You can also break a line at the pipe separator (|) $a = 2
character (assuming your line uses the pipeline): Bonus. To determine the number of lines, words, and switch ($a)
$args[-1] characters in a text file use this command: {
Get-ChildItem C:\Scripts | 1 {"The color is red."}
Sort-Object Length –Descending get-content c:\scripts\test.txt | 2 {"The color is blue."}
measure-object -line -word -character 3 {"The color is green."}
How to Use Colored Text 4 {"The color is yellow."}
To display text in a different color use the Write-Host default {"Other."}
cmdlet and specify a foreground color: How to Create Multi-Command Lines }
To put multiple commands on a single line, separate How to Write to a Text File
Write-Host "test" -foregroundcolor "green" those commands using a semicolon:
To save data to a text file use the Out-File cmdlet:
You can also specify a different background color: $a = 1,2,3,4,5; $b = $a[2]; Write-Host $b
How to Write For and For Each Loops
Get-Process | Out-File C:\Scripts\Test.txt To write a For statement use code similar to this:
Write-Host "test" -backgroundcolor "red"
To append data to an existing file, add the –append for ($a = 1; $a -le 10; $a++) {$a}
How to Make Comparisons parameter:
How to Insert a Paragraph Return Windows PowerShell cmdlets (like Where-Object) use a By comparison, a For Each statement might look like
special set of comparison operators, including those Get-Process | Out-File C:\Test.txt –append this:
To insert a paragraph return in your output use the shown in the following table.
newline character `n: You can also use the MS-DOS redirection characters (> foreach ($i in get-childitem c:\scripts)
Each of these operators can be made case sensitive by for write, >> for append) when using Windows {$i.extension}
Write-Host "Line 1.`nLine 2." adding a c immediately after the hyphen. For example, PowerShell. This command writes data to the file
-ceq represents the case-sensitive equals operator; -clt C:\Scripts\Test.txt:
is the case-sensitive less than operator.
How to Write in Reverse Video
Get-Process > C:\Scripts\Test.txt How to Write Do Loops
-lt Less than To write a Do loop use code like the following, replacing
To echo a message in reverse video use the Write- Another option is to use the Export-CSV cmdlet to save
-le Less than or equal to the code between the curly braces with the code to be
Warning cmdlet: data as a comma-separated-values file:
-gt Greater than executed on each iteration of the loop. Oh: and replacing
-ge Greater than or equal to Get-Process | Export-CSV C:\Test.csv the code inside the parentheses with the loop condition:
Write-Warning "An error has occurred."
-eq Equal to
-ne Not equal to $a = 1
-like Like (uses wildcards for do {$a; $a++}
matching) How to Print Data while ($a -lt 10)
How to Insert Comments
-notlike Not like (uses wildcards for To print data to the default printer use the Out-Printer
To insert a comment, use the pound sign (#): matching) $a = 1
cmdlet:
do {$a; $a++}
# This is a comment, not a line to be run. Get-Process | Out-Printer until ($a –gt 10)
Windows PowerShell Quick Reference Windows PowerShell Quick Reference

How to Create a COM Object How to Work with WMI How to Get Help How to Copy and Paste
To work with a COM object use the New-Object cmdlet To get computer information using WMI call the Get- To get complete help information for a Windows To enable simple copying and pasting in the Windows
followed by the –comobject parameter and the WMIObject cmdlet followed by the class name: PowerShell cmdlet, use the Get-Help cmdlet along with PowerShell console do the following:
appropriate ProgID: the –full parameter. For example, to view the help
Get-WMIObject Win32_BIOS information for the Get-Process cmdlet type the Start Windows PowerShell, then click the icon in the
$a = New-Object -comobject ` following: upper left-hand corner and choose Properties.
"Excel.Application" If the class you are interested in does not reside in the In the Windows PowerShell Properties dialog box, on
$a.Visible = $True cimv2 namespace simply include the –namespace Get-Help Get-Process –full the Options tab, select QuickEdit Mode and then
parameter: click OK.
To view the example commands for a cmdlet use the
How to Create a .NET Object Get-WMIObject SystemRestore ` –examples parameter: To copy text in the console window select the text and
-namespace root\default then press ENTER. To paste text into the window click
To instantiate and use a .NET Framework object enclose Get-Help Get-Process –examples the right mouse button.
the class name in square brackets, then separate the To access data on another computer use the
class name and the method using a pair of colons: –computername parameter: If you can’t remember the exact name for a cmdlet use
Get-Command to retrieve a list of all the cmdlets
[system.Net.DNS]::resolve("207.46.198.30") Get-WMIObject Win32_BIOS ` available to you:
–computername atl-ws-01
How to Run a Script
To create an object reference to a .NET Framework Get-Command To run a script from within Windows PowerShell, type the
object use the New-Object cmdlet: To limit returned data, use a WQL query and the –query full path to the script (or type the script name if the script
parameter: For a list of available aliases, use the Get-Alias cmdlet: is stored in a folder that is part of your Windows path):
$a = new-object `
-type system.diagnostics.eventlog ` Get-WMIObject -query ` Get-Alias C:\Scripts\Test.ps1
-argumentlist system "Select * From Win32_Service `
Where State = 'Stopped'" If the path name includes blank spaces you must preface
Note. This is a cursory overview of working with .NET. the path with an ampersand and enclose the path in
The two techniques shown here will not necessarily work How to Change Security Settings
double quotes. For example:
with all .NET classes. To run scripts from within Windows PowerShell you will
How to Bind to Active Directory need to change your security settings; by default, &"C:\Scripts\My Scripts\test.ps1"
To bind to an Active Directory account use the LDAP PowerShell only runs scripts signed by a trusted
How to Select Properties provider: authority. To enable PowerShell to run all locally-created From outside Windows PowerShell (e.g., from the Run
scripts (regardless of whether or not they have been dialog box or from a Cmd.exe window) you must call
To work with or display specified properties of a Windows PowerShell and then pass the script path as an
$a = [adsi] "LDAP://cn=kenmyer, ` signed) use the following command:
collection, pipe the returned results to the Select-Object
ou=Finance, dc=fabrikam, dc=com" argument to that call:
cmdlet: Set-ExecutionPolicy RemoteSigned
Listing all the objects in an OU is a little more powershell.exe –noexit C:\Scripts\Test.ps1
Get-Process | Select-Object Name, Company
complicated; however, one relatively easy way to
accomplish this task is to bind to the OU and then use The -noexit parameter ensures that the PowerShell
the PSBase_GetChildren() method to retrieve a How to “Interrogate” an Object window remains open after the script finishes running.
How to Sort Data
collection of items stored in that OU:
To sort data returned by Windows PowerShell simply To get information about the properties and methods of
pipe that data to the Sort-Object cmdlet, specifying the $objOU = [ADSI]` an object retrieve an instance of that object and then
property you want to sort by: "LDAP://ou=Finance,dc=fabrikam,dc=com" “pipe” the object to the Get-Member cmdlet. For
example, this command returns the properties and How to Get More Information
$users = $objOU.PSBase.Get_Children()
Get-Process | Sort-Object ID $users | Select-Object displayName methods available when working with processes:
For more information on writing
You can also add the –descending or -ascending Get-Process | Get-Member Windows PowerShell scripts visit the
parameters to specify a sort order: TechNet Script Center at
How to Bind to Local Accounts http://www.mcrosoft.com/technet/
Get-Process | Sort-Object ID –descending scriptcenter/hubs/msh.mspx. Start with
To bind to a local account, use the WinNT provider: How to Clear the Console Window the PowerShell Week webcasts and the
You can even sort by multiple properties: series A Task-Based Introduction to
$a = [adsi] "WinNT://atl-ws-01/kenmyer" To clear the PowerShell window, use the Clear-Host
Windows PowerShell.
$a.FullName function (or its alias, cls).
Get-Process | Sort-Object ProcessName, ID
Filename: powershell_reference.doc
Directory: C:\Documents and Settings\Scott Sweeney\Desktop
Template: C:\Documents and Settings\Scott Sweeney\Application
Data\Microsoft\Templates\Normal.dot
Title:
Subject:
Author: Greg Stemp
Keywords:
Comments:
Creation Date: 5/30/2007 6:55:00 PM
Change Number: 11
Last Saved On: 5/31/2007 10:12:00 AM
Last Saved By: Greg Stemp
Total Editing Time: 44 Minutes
Last Printed On: 1/22/2008 9:46:00 PM
As of Last Complete Printing
Number of Pages: 2
Number of Words: 9 (approx.)
Number of Characters: 55 (approx.)

You might also like