PowerShell Quick Reference Dimension IT v3.03
PowerShell Quick Reference Dimension IT v3.03
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
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
Dir –Recurse | Where { $_.length –gt 100MB } | Group Length | Where { $_.count –gt 1 } # displays large files with exact same size, might be duplicate
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)
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
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