You are on page 1of 2

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 a 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:
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 by $a = "white"
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 collection, To insert a line break into a Windows PowerShell script {"The color is blue."}
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 Select
"This is a continuation of the line." Case statement:
You can reference the last item in a collection by using the $a[-1]
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 those How to Write to a Text File
Write-Host "test" -foregroundcolor "green"
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 this:
Get-Process | Out-File C:\Test.txt –append
special set of comparison operators, including those
To insert a paragraph return in your output use the newline shown in the following table. foreach ($i in get-childitem c:\scripts)
character `n: You can also use the MS-DOS redirection characters (> {$i.extension}
Each of these operators can be made case sensitive by for write, >> for append) when using Windows PowerShell.
Write-Host "Line 1.`nLine 2." adding a c immediately after the hyphen. For example, This command writes data to the file C:\Scripts\Test.txt:
-ceq represents the case-sensitive equals operator; -clt is
Get-Process > C:\Scripts\Test.txt
the case-sensitive less than operator.
How to Write in Reverse Video How to Write Do Loops
Another option is to use the Export-CSV cmdlet to save
-lt Less than To write a Do loop use code like the following, replacing
To echo a message in reverse video use the Write- data as a comma-separated-values file:
-le Less than or equal to the code between the curly braces with the code to be
Warning cmdlet: -gt Greater than executed on each iteration of the loop. Oh: and replacing
Get-Process | Export-CSV C:\Test.csv
-ge Greater than or equal to 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. until ($a –gt 10)
Get-Process | Out-Printer
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 following: Start Windows PowerShell, then click the icon in the upper
$a = New-Object -comobject ` left-hand corner and choose Properties.
"Excel.Application" If the class you are interested in does not reside in the Get-Help Get-Process –full In the Windows PowerShell Properties dialog box, on
$a.Visible = $True cimv2 namespace simply include the –namespace the Options tab, select QuickEdit Mode and then
parameter: To view the example commands for a cmdlet use the click OK.
–examples parameter:
How to Create a .NET Object Get-WMIObject SystemRestore ` To copy text in the console window select the text and then
-namespace root\default Get-Help Get-Process –examples press ENTER. To paste text into the window click the right
To instantiate and use a .NET Framework object enclose mouse button.
the class name in square brackets, then separate the To access data on another computer use the If you can’t remember the exact name for a cmdlet use
class name and the method using a pair of colons: –computername parameter: Get-Command to retrieve a list of all the cmdlets available
to you:
[system.Net.DNS]::resolve("207.46.198.30") Get-WMIObject Win32_BIOS `
–computername atl-ws-01 Get-Command How to Run a Script
To create an object reference to a .NET Framework object To run a script from within Windows PowerShell, type the
use the New-Object cmdlet: To limit returned data, use a WQL query and the –query For a list of available aliases, use the Get-Alias cmdlet: full path to the script (or type the script name if the script is
parameter: stored in a folder that is part of your Windows path):
$a = new-object ` Get-Alias
-type system.diagnostics.eventlog ` Get-WMIObject -query ` 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 the path with an ampersand and enclose the path in
two techniques shown here will not necessarily work with How to Change Security Settings double quotes. For example:
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 authority.
How to Select Properties provider: To enable PowerShell to run all locally-created scripts From outside Windows PowerShell (e.g., from the Run
(regardless of whether or not they have been signed) use dialog box or from a Cmd.exe window) you must call
To work with or display specified properties of a collection,
$a = [adsi] "LDAP://cn=kenmyer, ` the following command: Windows PowerShell and then pass the script path as an
pipe the returned results to the Select-Object cmdlet:
ou=Finance, dc=fabrikam, dc=com" argument to that call:
Set-ExecutionPolicy RemoteSigned
Get-Process | Select-Object Name, Company
Listing all the objects in an OU is a little more complicated; powershell.exe –noexit C:\Scripts\Test.ps1
however, one relatively easy way to accomplish this task is
to bind to the OU and then use the The -noexit parameter ensures that the PowerShell
PSBase_GetChildren() method to retrieve a collection of How to “Interrogate” an Object window remains open after the script finishes running.
How to Sort Data
items stored in that OU:
To sort data returned by Windows PowerShell simply pipe To get information about the properties and methods of an
that data to the Sort-Object cmdlet, specifying the $objOU = [ADSI]` object retrieve an instance of that object and then “pipe”
property you want to sort by: "LDAP://ou=Finance,dc=fabrikam,dc=com" the object to the Get-Member cmdlet. For example, this
$users = $objOU.PSBase.Get_Children() command returns the properties and methods available How to Get More Information
Get-Process | Sort-Object ID $users | Select-Object displayName 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://technet.microsoft.com/en-
Get-Process | Sort-Object ID –descending us/scriptcenter/dd742419.aspx.
To bind to a local account, use the WinNT provider: How to Clear the Console Window
You can even sort by multiple properties: To clear the PowerShell window, use the Clear-Host
$a = [adsi] "WinNT://atl-ws-01/kenmyer"
$a.FullName function (or its alias, cls).
Get-Process | Sort-Object ProcessName, ID

You might also like