0% found this document useful (0 votes)
35 views

Windows Powershell Quick Reference Windows Powershell Quick Reference

This document provides a quick reference for common tasks in Windows PowerShell, summarizing how to access command line arguments, use colored text, insert line breaks, read and write files, use comparisons, write conditional statements, loops, and more. It offers concise code examples and explanations for over 40 different Windows PowerShell concepts and techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Windows Powershell Quick Reference Windows Powershell Quick Reference

This document provides a quick reference for common tasks in Windows PowerShell, summarizing how to access command line arguments, use colored text, insert line breaks, read and write files, use comparisons, write conditional statements, loops, and more. It offers concise code examples and explanations for over 40 different Windows PowerShell concepts and techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Windows PowerShell Quick Reference

How to Access Arguments


To access command-line arguments used when starting
a script use the automatic variable $args. You can cycle
through the individual arguments in the $args collection
by using code similar to this:

$args[0]
You can reference the last item in a collection by using
the index number 1:
$args[-1]

How to Use Colored Text


To display text in a different color use the Write-Host
cmdlet and specify a foreground color:
Write-Host "test" -foregroundcolor "green"
You can also specify a different background color:

To solicit input from a user, use the Read-Host cmdlet,


followed by the prompt to be displayed:

To read the contents of a text file into a variable, call the


Get-Content cmdlet followed by the path to the text file:

$a = Read-Host "Please enter your name"

$a = Get-Content C:\Scripts\Test.txt

How to Insert Line Breaks


To insert a line break into a Windows PowerShell script
use the backtick (`) :
Write-Host `
"This is a continuation of the line."
You can also break a line at the pipe separator (|)
character (assuming your line uses the pipeline):
Get-ChildItem C:\Scripts |
Sort-Object Length Descending

$a = 1,2,3,4,5; $b = $a[2]; Write-Host $b

How to Make Comparisons


To insert a paragraph return in your output use the
newline character `n:
Write-Host "Line 1.`nLine 2."

How to Write in Reverse Video


To echo a message in reverse video use the WriteWarning cmdlet:
Write-Warning "An error has occurred."

How to Insert Comments


To insert a comment, use the pound sign (#):
# This is a comment, not a line to be run.

Each line in the file ends up as an item in the array $a. If


you want to access a single line in the file you can simply
specify the index number corresponding to that line:
$a[0]
This command echoes back the last line in $a:
$a[-1]
Bonus. To determine the number of lines, words, and
characters in a text file use this command:
get-content c:\scripts\test.txt |
measure-object -line -word -character

How to Create Multi-Command Lines


To put multiple commands on a single line, separate
those commands using a semicolon:

Write-Host "test" -backgroundcolor "red"

How to Insert a Paragraph Return

How to Read a Text File

How to Solicit Input

foreach ($i in $args) {$i}


To access a particular argument use the collection index
number, with 0 representing the first item in the
collection, 1 representing the second item, etc:

Windows PowerShell Quick Reference

Windows PowerShell cmdlets (like Where-Object) use a


special set of comparison operators, including those
shown in the following table.
Each of these operators can be made case sensitive by
adding a c immediately after the hyphen. For example,
-ceq represents the case-sensitive equals operator; -clt
is the case-sensitive less than operator.
-lt
-le
-gt
-ge
-eq
-ne
-like
-notlike

Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
Like (uses wildcards for
matching)
Not like (uses wildcards for
matching)

How to Write Conditional Statements


To write an If statement use code similar to this:
$a = "white"
if ($a -eq "red")
{"The color is red."}
elseif ($a -eq "white")
{"The color is white."}
else
{"The color is blue."}
Instead of writing a series of If statements you can use a
Switch statement, which is equivalent to VBScripts
Select Case statement:
$a = 2
switch ($a)
{
1 {"The
2 {"The
3 {"The
4 {"The
default
}

color is red."}
color is blue."}
color is green."}
color is yellow."}
{"Other."}

How to Write to a Text File


To save data to a text file use the Out-File cmdlet:

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:

To append data to an existing file, add the append


parameter:

for ($a = 1; $a -le 10; $a++) {$a}

Get-Process | Out-File C:\Test.txt append

By comparison, a For Each statement might look like


this:

You can also use the MS-DOS redirection characters (>


for write, >> for append) when using Windows
PowerShell. This command writes data to the file
C:\Scripts\Test.txt:
Get-Process > C:\Scripts\Test.txt
Another option is to use the Export-CSV cmdlet to save
data as a comma-separated-values file:
Get-Process | Export-CSV C:\Test.csv

How to Print Data


To print data to the default printer use the Out-Printer
cmdlet:
Get-Process | Out-Printer

foreach ($i in get-childitem c:\scripts)


{$i.extension}

How to Write Do Loops


To write a Do loop use code like the following, replacing
the code between the curly braces with the code to be
executed on each iteration of the loop. Oh: and replacing
the code inside the parentheses with the loop condition:
$a = 1
do {$a; $a++}
while ($a -lt 10)
$a = 1
do {$a; $a++}
until ($a gt 10)

Windows PowerShell Quick Reference


How to Create a COM Object
To work with a COM object use the New-Object cmdlet
followed by the comobject parameter and the
appropriate ProgID:
$a = New-Object -comobject `
"Excel.Application"
$a.Visible = $True

How to Create a .NET Object


To instantiate and use a .NET Framework object enclose
the class name in square brackets, then separate the
class name and the method using a pair of colons:
[system.Net.DNS]::resolve("207.46.198.30")
To create an object reference to a .NET Framework
object use the New-Object cmdlet:
$a = new-object `
-type system.diagnostics.eventlog `
-argumentlist system
Note. This is a cursory overview of working with .NET.
The two techniques shown here will not necessarily work
with all .NET classes.

How to Select Properties


To work with or display specified properties of a
collection, pipe the returned results to the Select-Object
cmdlet:
Get-Process | Select-Object Name, Company

How to Sort Data


To sort data returned by Windows PowerShell simply
pipe that data to the Sort-Object cmdlet, specifying the
property you want to sort by:
Get-Process | Sort-Object ID
You can also add the descending or -ascending
parameters to specify a sort order:
Get-Process | Sort-Object ID descending
You can even sort by multiple properties:
Get-Process | Sort-Object ProcessName, ID

Windows PowerShell Quick Reference

How to Work with WMI


To get computer information using WMI call the GetWMIObject cmdlet followed by the class name:
Get-WMIObject Win32_BIOS
If the class you are interested in does not reside in the
cimv2 namespace simply include the namespace
parameter:
Get-WMIObject SystemRestore `
-namespace root\default

How to Get Help


To get complete help information for a Windows
PowerShell cmdlet, use the Get-Help cmdlet along with
the full parameter. For example, to view the help
information for the Get-Process cmdlet type the
following:
Get-Help Get-Process full
To view the example commands for a cmdlet use the
examples parameter:
Get-Help Get-Process examples

To access data on another computer use the


computername parameter:
Get-WMIObject Win32_BIOS `
computername atl-ws-01

If you cant remember the exact name for a cmdlet use


Get-Command to retrieve a list of all the cmdlets
available to you:
Get-Command

To limit returned data, use a WQL query and the query


parameter:
Get-WMIObject -query `
"Select * From Win32_Service `
Where State = 'Stopped'"

To bind to an Active Directory account use the LDAP


provider:
$a = [adsi] "LDAP://cn=kenmyer, `
ou=Finance, dc=fabrikam, dc=com"
Listing all the objects in an OU is a little more
complicated; however, one relatively easy way to
accomplish this task is to bind to the OU and then use
the PSBase_GetChildren() method to retrieve a
collection of items stored in that OU:
$objOU = [ADSI]`
"LDAP://ou=Finance,dc=fabrikam,dc=com"
$users = $objOU.PSBase.Get_Children()
$users | Select-Object displayName

To copy text in the console window select the text and


then press ENTER. To paste text into the window click
the right mouse button.

How to Run a Script

Get-Alias

C:\Scripts\Test.ps1

To run scripts from within Windows PowerShell you will


need to change your security settings; by default,
PowerShell only runs scripts signed by a trusted
authority. To enable PowerShell to run all locally-created
scripts (regardless of whether or not they have been
signed) use the following command:
Set-ExecutionPolicy RemoteSigned

How to Interrogate an Object


To get information about the properties and methods of
an object retrieve an instance of that object and then
pipe the object to the Get-Member cmdlet. For
example, this command returns the properties and
methods available when working with processes:

How to Bind to Local Accounts


$a = [adsi] "WinNT://atl-ws-01/kenmyer"
$a.FullName

Start Windows PowerShell, then click the icon in the


upper left-hand corner and choose Properties.
In the Windows PowerShell Properties dialog box, on
the Options tab, select QuickEdit Mode and then
click OK.

For a list of available aliases, use the Get-Alias cmdlet:

Get-Process | Get-Member

To bind to a local account, use the WinNT provider:

To enable simple copying and pasting in the Windows


PowerShell console do the following:

To run a script from within Windows PowerShell, type the


full path to the script (or type the script name if the script
is stored in a folder that is part of your Windows path):

How to Change Security Settings


How to Bind to Active Directory

How to Copy and Paste

How to Clear the Console Window


To clear the PowerShell window, use the Clear-Host
function (or its alias, cls).

If the path name includes blank spaces you must preface


the path with an ampersand and enclose the path in
double quotes. For example:
&"C:\Scripts\My Scripts\test.ps1"
From outside Windows PowerShell (e.g., from the Run
dialog box or from a Cmd.exe window) you must call
Windows PowerShell and then pass the script path as an
argument to that call:
powershell.exe noexit C:\Scripts\Test.ps1
The -noexit parameter ensures that the PowerShell
window remains open after the script finishes running.

How to Get More Information


For more information on writing
Windows PowerShell scripts visit the
TechNet Script Center at
http://technet.microsoft.com/enus/scriptcenter/dd742419.aspx.

You might also like