0% found this document useful (0 votes)
16 views2 pages

PowerShell Quick Reference Dimension IT v3.03

This document is a PowerShell quick reference guide that provides essential commands, aliases, operators, and examples for using PowerShell effectively. It includes sections on built-in help functionality, working with files, security, looping, functions, and Active Directory commands. Additionally, it highlights new features in PowerShell 3 and offers resources for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

PowerShell Quick Reference Dimension IT v3.03

This document is a PowerShell quick reference guide that provides essential commands, aliases, operators, and examples for using PowerShell effectively. It includes sections on built-in help functionality, working with files, security, looping, functions, and Active Directory commands. Additionally, it highlights new features in PowerShell 3 and offers resources for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

PowerShell Quick Reference v3.03 by Dimitri Koens - www.dimensionit.

tv
Please contact me with questions, remarks, etc regarding this document at dimitrikoens at gmail.com. Join me on
Linked in and Twitter to receive valuable information regarding PowerShell, SCOM, SQL Server and Virtualization.

Quick Start
Get-Process # displays a list of running processes
Get-Process | Select-Object Name, Company # selects several columns
Get-Process | Select-Object Name, Company | Format-Table -AutoSize # uses minimal column width
Get-Process | Select-Object Name, Company | Format-List # displays a list instead of a table
Get-Process | Sort-Object ID –Descending # sorts on process id instead of name
Get-Process | Where-Object { $_.vm –gt 150MB } # selects processes where virtual memory is greater than 150MB
Get-Process | Select-Object Name, @{Name=”Virtual Memory”; Expression={$_.vm}} # changes the name of a column
Get-Process | Select-Object Name,VM,WS,@{Label="TotalMemory";Expression={$_.vm + $_.ws}} # introduces a calculated column
Get-Process | Select-Object Name,VM,WS,@{Label="Total Memory in MB";Expression={[int](($_.vm + $_.ws)/1MB)}} # calculated column and rounded to integer

Built-in Help functionality


Get-Help Get-Command -CommandType Cmdlet # display all native PowerShell cmdlets
Get-Help Get-Process –full Get-Process | Get-Member # display the properties and methods of the output
Get-Help Get-Process –examples # view the example commands
Get-Help about* # lists all the about-articles, use the full article name to view its # The following two examples help you to protect you from ... you!
contents, e.g. about_scripts Get-Process PowerShell | Stop-Process –whatif # displays the command without
actually executing it
Get-Command # display all commands Get-Process PowerShell | Stop-Process –confirm # asks for confirmation
Get-Command *process* # display all commands containing the word “process”

Aliases (and functions denoted by *)


All default cmdlets with “-Object” as a noun are aliased to their verb without “-Object”, e.g. Sort is an alias of Sort-Object, Select is an alias of Select-Object
Get-Alias | Group-Object Definition # display all possible aliases per command
Command Alias Command Alias Command Alias
Clear-Host cls, clear Get-Help help *, man Rename-Item rni, ren
Copy-Item copy, cpi, cp Get-Member gm Select-String sls (Psv3+)
ForEach-Object foreach, % Get-Process gps, ps Set-Location sl, cd, chdir
Format-List FL Get-WmiObject gwmi Start-Sleep sleep
Format-Table FT Move-Item mi, move, mv Stop-Process spps, kill
Get-ChildItem gci, dir, ls Out-Host oh Where-Object where, ?
Get-Command gcm Powershell_ise.exe ise (PSv2+) Write-Output echo, write
Get-Content gc, type, cat Remove-Item ri, del, erase, rmdir, rd, rm
New alias expected in Windows 2015: Set-Alias Ping Test-Connection. Select-String has an alias in PSv3: sls. Shouldn’t this have been ‘grep’? ;)

Operators (most of them), Get-Help about _Operators


Operator Meaning Operator Meaning
+, -, *, /, % add, subtract, multiply, divide, remainder =, +=, -=, *=, /=, %= assign/change/append one or more values to variables
-eq, -ne Equal, not equal: 5 –eq 5 -match, -notmatch, -cmatch regular expression match: “Rick” -match "[DMNR]ick"
-gt, -ge greater than, greater than or equals: 6 –gt 5 -contains, -notcontains Array contains specific value: “red”, “blue” –contains “blue”
-lt, -le less than, less than or equals: 5 –lt 6 -and, -or, -xor, -not, ! Logical operators
-like, -notlike, -clike wildcard comparison: "Samantha" -like "sam*" -f Formatting: $a=2987654; “free space: {0:N0} bytes” -f $a

Punctuation Marks
( expression ) { code block } [ item in array ] “string with automatic variable expansion”
` backtick is the escape character, mostly found on the key combined with tilde-sign ~ ‘string without automatic variable expansion‘

Keyboard shortcuts
Tab: command completion F7: display history popup, Alt-F7: clears command buffer Ctrl , Ctrl : jump one word left or right
Esc: clear the command line F8: lookup last command that starts with current input. Try | More: <Ctrl-C> quit, <q> quit, <space> scroll page,
this: Get-Process; <enter>; Get<F8> <enter> scroll one line
Use arrow up and down to browse previous commands Home, End: jump to start or end of current command line Within ISE: F5 = Run, F8 = Run Selection

Security
The .ps1 extension Execution Policy (Set- and Get-ExecutionPolicy) To prevent command hijacking
Associated with Notepad. When a user receives a Restricted (default), AllSigned, RemoteSigned, Unrestricted (not You can only run commands from the current
PowerShell script through e-mail and doubleclicks it recommended) location by specifying the path to the script.
then the script just opens in notepad instead of Remote scripts: not on local fixed disks, like CD’s/DVD’s, drive mappings to Example: .\script.ps1 instead of script.ps1.
executing (like the i-love-you virus did). network shares, attachements in e-mail and chat-programs.

Variables
$_ # Current object in the pipeline $Host # Displays the PowerShell version
$Home # Full path to the user’s home directory $i = 1 # storing value 1 in variable $i
$PSHome # Full path to the installation directory $i++ # incrementing $i with 1, resulting in 2

Working with files


Get-Process | Out-File p.txt –append Get-Process | Export-CSV p.csv Get-Process | Export-CliXML p.xml
Import-CSV p.csv # displays using Format-List because there are more than four columns and object type is not recognized
Import-CliXML p.xml # displays using Format-Table because object type is recognized (try to add: | Get-Member)
Compare-Object (Import-Clixml p.xml) (Get-Process) -Property name # compare processes stored in XML with current situation

Dir –Recurse | Where { $_.length –gt 100MB } | Group Length | Where { $_.count –gt 1 } # displays large files with exact same size, might be duplicate

This document is licensed under a Creative Commons Attribution-NonCommercial-NoDerivsCC BY-NC-ND license.


What’s New in PowerShell 3
Requirements: W2008 R2 SP1, W7 SP1, .NET 4.0, download and install KB2506146 or KB2506143.
Note: install ISE first before upgrading to PowerShell 3 on Windows 2008 (R2) or Windows 7!
Automatic module loading: no need to use e.g. “Import-Module ActiveDirectory” anymore.
ISE changes: IntelliSense, brace matching, error indication, start snippets, rich copy, block select (Alt+Mouse), context sensitive help (F1), many more!
New modules: BranchCache, DirectAccess, Dism, DHCP, DNS, iSCSI, NetAdapter, NetTCPIP, NetworkSecurity, PKI, Printing, Schedul ed Tasks, SMB, Storage, many more!
$PSItem # same function as $_: current item in pipeline
Show-Command # shows a GUI for a specific Cmdlet
Get-Process | Out-GridView -OutputMode Multiple | Stop-Process # Out-GridView has an OutputMode parameter: select several items and press OK
Install-WindowsFeature WindowsPowerShellWebAccess -IncludeManagementTools –Restart # Installs PowerShell Web Access feature
Install-PswaWebApplication -UseTestCertificate # creates the virtual directory and appliation pool using a test certificate
Add-PswaAuthorizationRule * * * # Creates an authorization rule. Now browse with any supported browser (IE, Chrome!, Firefox!, Safari!) to http://<server>/pswa

Looping
for ($i = 1; $i -le 10; $i++) { $i } # displays numbers 1 through 10. See the Active Directory section for a practical example

While loop only executes when condition is true Do … While loop, always executes, at least once Do … Until loop, always executes, at least once
$i = 1 $a = 1 $a = 1
While ($i -le 10) { $i; $i++ } Do {$a; $a++} While ($a -lt 10) Do {$a; $a++} Until ($a –gt 10)

Typical example of a Do … Until loop


$RequiredLength = 12
Do {
$password = read-host -prompt "Password, please"
if ($password.length -lt $RequiredLength) { "password is too short!" }
} Until ($password.length -ge $RequiredLength)

Functions
Function Get-NewestEventlog { Param ($log=”system”, $newest=5) Get-Eventlog $log –newest $newest }
Get-NewestEventlog # try with parameters like –log application –newest 10

WMI
Get-WmiObject –list # lists all WMI classes
# inspecting shares through WMI # automating defragmentation (please check with your SAN administrator!)
Get-WmiObject Win32_Share $Cvolume = Get-WmiObject Win32_Volume | Where { $_.name –eq "C:\" }
$share = Get-WmiObject Win32_Share | Where { $_.Name –eq “C$” } $df = $Cvolume.DefragAnalysis() # can take several minutes or even hours
$share | Get-Member # check name and caption $df # inspecting the result
# we’ll need the wmiclass type to create objects through WMI If ($df.DefragRecommended) { $Cvolume.defrag($true) }
$share=[WMICLASS]"Win32_Share"
$share.create("C:\", "mynewshare", 0) # creating a new share

Get-WmiObject Win32_OperatingSystem –computername (Get-Content servers.txt) | Format-Table __SERVER,Version,ServicePackMajorVersion,ServicePackMinorVersion


Get-WmiObject Win32_LogicalDisk -Filter 'DriveType=3' –ComputerName (Get-Content computers.txt) |
Format-Table __SERVER,DeviceID,FreeSpace,@{Label='PercentFree';Expression={$_.FreeSpace / $_.Size};FormatString='{0:#0.00%}'}

Active Directory
Requirements: PowerShell v2, Active Directory Module for Windows PowerShell (on a Domain Controller, also part of RSAT). Open port TCP/9389.
Requirements: Windows Server 2008 R2 Domain Controller or install ADMGS on a W2003/2008 Domain Controller.
Import-Module ActiveDirectory # imports the Active Directory module for PowerShell
Get-Command –module ActiveDirectory # displays all 76 commands in PowerShell v2
New-ADOrganizationalUnit “Employees” -Path "DC=Contoso,DC=com" # creates a new OU
Get-ADOrganizationalUnit -Filter “*” | FT Name, DistinguishedName –AutoSize
New-ADUser TestUserA # creates a disabled user in the Users container

# The next script takes a plain text password as input and creates an enabled user account in the Employees OU
$userpwd = ConvertTo-SecureString -AsPlainText "Pa$$w0rd" –Force # converts plaintext to secure string
New-ADUser TestUserB -AccountPassword $userpwd -Enabled $true -Path 'OU=Employees,DC=Contoso,DC=com'

For ($i=1; $i –le 10; $i++) { New-ADUser –name Testuser$i } # creates ten new testusers

Background Jobs Remoting


Start-Job { Get-Process PowerShell } Requirements: PowerShell v2 on local and remote systems. Enable Remoting on
Get-Job remote system. Open port TCP/5985.
Get-Job -Id 1| Receive-Job # use the -Keep parameter to keep the data in memory Enable-PSRemoting # Run this on the remote system. Use –Force optionally.
Start-Job { Sleep 60 } # starts a new job which just waits for 60 seconds Enter-PSSession –ComputerName Server2
Wait-Job -Id 3 # wait for a job to complete, or use: Stop-Job -Id 3 # stops job # use your PowerShell skills now on the remote machine
Remove-Job -Id 3 # remove a completed job Exit-PSSession
Free ebook about remoting: http://www.ravichaganti.com/blog/?page_id=1301

Error handling and Debugging


$ErrorActionPreference # displays the default action when an error occurs
Dir c:, x:, c: # should result in a file listing of the c-drive, followed by an error, followed by a listing of the c-drive
$ErrorActionPreference = ‘SilentlyContinue’ # or ‘Continue’ or ‘Inquire’ or ‘Stop’
Dir c:, x:, c: # should result in two file listings of the c-drive, no more error
# Use the –ErrorAction parameter to use a other error action for the current command only
$Error[0] | Get-Member # displays information about the last error

More information on the Internet (and the previous page…)


http://blogs.msdn.com/b/powershell/ http://www.computerperformance.co.uk/powershell/
http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx http://powerwf.com/products.aspx
http://poshoholic.com/ http://social.technet.microsoft.com/wiki/contents/articles/windows-powershell-
http://thepowershellguy.com/ survival-guide.aspx
http://blogs.msdn.com/b/kathykam/archive/2006/03/29/564426.asp
http://www.powershellmagazine.com/

This document is licensed under a Creative Commons Attribution-NonCommercial-NoDerivsCC BY-NC-ND license.

You might also like