Basic PowerShell CheatSheat

Posted On 2017-12-10 by dwirch
Keywords:
Tags: Powershell Scripting Tip Windows
Views: 168


We all need to peek at the answers from time to time. This post is simply a quick reference guide for basic PowerShell tips, tricks, how-to's, explanations, etc.

I've found these items useful in the past, and hope you do as well.

Links to Microsoft or other documentation have made where applicable, and I'll keep adding to it.

Variables
$var = "string"Assign variable
[Type]$var="typedVar"Assign strong typed variable
[ValidateRange(1,9)][int]$x=1Assign strong typed attribute controlled variable
$a,$b,$c = 0 or $a,$b = 'a','b'Assign multiple variables
$a,$b = $b,$aFlip variables
Scopesglobal, local, private or script
$global:var = "var"Assign global scoped variable
Arrays
"a", "b", "c"Array of strings
@()Empty array
1,(2,3),4Array within array
,"hi"Array of one element
$arr[5]Sixth element of array
$arr[2..20]Return elements 3 thru 21
$arr[-1]Return last array element
$arr[-3..-1]Display last threeelementsofarray
$arr[1,4+6..9]Elements at index positions 1,4, 6 to 9
@(Get-Process)Force result to an array
$arr[($arr.length-1)..0]Reverse array
$arr[1] += 200Add to existing array item value
$b = $arr[0,1 + 3..6]New array from elements of $arr array
$z = $arrA + $arrBCombine two arrays into single array
Arrays
$hash = @{}Create empty hash table
@{foo=1; bar='value2'}Create, initialize hash table
[ordered]@{a=1; b=2; c=3}Create ordered dictionary
$hash.key1 = 1Assign 1 to key key1
$hash.key1Return value of key1
$hash["key1"]Return value of key1
$hash.GetEnumerator | sort KeySort hash table by Key
[pscustomobject]@{x=1;z="z"}Create custom object
Strings
"$var expand"String with expansion "
'$var no expand'String with no expansion '
@" Here-String "@Here-String -quotes, expressions, etc. Single quotes for no expressions
Comments, Escape Characters, Backtick
#CommentComment
<# comment #>Multiline comment
"A `"test`""Escape char `
`tTab
`nNew line
`Line continuation
Text and Files Basics
Get-LocationGet current directory
Set-LocationChange directory
Get-ContentGet content of file
Add-ContentAppend content
Set-ContentSet content of file
Out-FileFormatted text to file
Out-NullDiscard output
Out-StringConvert to strings
Copy-ItemCopy items
Remove-ItemRemove items
Move-ItemMove items
Rename-ItemRename item
Set-ItemSet contents of file
Clear-itemClear contents of file
New-ItemNew empty file or dir
Objects
(Get-Date).DateDate property of object from Get-Date
Get-Date | Get-MemberList properties and methods of object
[DateTime]::NowStatic properties referenced with "::"
"string".ToUpper()Use ToUpper() Method on string
[system.Net.Dns]::GetHostByAddress("127.0.0.1")Use static method to get host name with "::"
$excel = new-object -com excel.applicationCreate a new Excel COM object to work with
Flow Control
If($x -eq 5){} Elseif($x -gt 5) {} Else{}If
$x = 1; while($x -lt 10){$x;$x++}While
For($i=0; $i -lt 10; $i++){ $i }For
Foreach($file in dir C:\){$file.Name}Foreach
1..10 | foreach{$_}Foreach
Switch -options (<values to switch on >)
PatternX {statement}
Default {Default Statement}
Switch
Assignment, Logical, Comparison Operators
=,+=,-=,*=,/=,%=,++,--Assign one or more values to variable
-and, -or, -xor, -not, !Connect expressions / statements
-eq, -neEqual, not equal
-gt, -geGreater than, greater than or equal
-lt, -leLess than, less than or equal to
-replaceReplacement -"Hi" -replace "H", "P"
-match,-notmatchRegular expression match
-like,-notlikeWildcard matching
-contains,-notcontainsTRUE if value on right in array on left
-in, -notinReverse of contains,notcontains
Other Operators
-SplitSplit a string "abcdefghi" -split "de"
-joinJoins multiple strings "abc","def" -join ";"
..Range operator 1..10 | foreach {$_ * 5}
-is,-isnotBoolean -is object instance of specified .NET type
-asConvert input object to specified .NET type
-fFormat strings 1..10 | foreach { "{0:N2}" -f $_ }
[ ]Cast operator. [datetime]$birthday = "1/10/66"
$( )Subexpression operator
@( )Array subexpression operator
&The call/invocation operator.
Filter, Sort, Group, and Format
dir C:\pub | where-object LastWriteTime -gt (Get-Date).addDays(-1)Files in C:\pub with lastwritetime greater than yesterday
ps | where-object {$_.path -like "C:\windows\system32*" -and $_.company -notlike "Microsoft*"}Processes where path includes system32 and company doesn't start with Microsoft
ps Explorer | select-object -Property ProcessName -ExpandProperty Modules | format-listGet explorer processes, select processname, expand modules property array
ps | Sort-Object -Property WorkingSet | Select-Object -Last 5Sort Processes by workingset, select last 5
"a","b","a" | Select-Object -UniqueReturn only unique -returns @(a b)
Get-Service | Group-Object StatusGroup services by their Status
dir | Group-Object {$_.Length -gt 100KB}Group objects bigger/smaller than 100 KB
Get-Content C:\pcs.txt | Select-String "q-" | sls "win7"Select strings with "q-", "win7" from pcs.txt
ps | Format-Table -Property Name, StartTime -AutoSizeFormat ps output showing Name, StartTime properties, autosize the table
ps | Format-table ProcessName, @{ Label = "Total Run Time"; Expression={(Get-Date) -$_.StartTime}}Table showing processname, custom label/expression showing run time.
Get-EventLog -Log System | Select -first 5 | Format-table -wrapGet first 5 events in system log, wrap display
gi C:\Users | format-list -property *Get all properties from C:\users in list format
"{0}`t{1]`n" -f $a, 5-f operator to construct strings. {0} replaced with $a, {1} with 5 etc.
Drive letter accessible locations
Alias:Aliases in current session
Cert:Certificate store for user
Env:Environment variables
Function:All functions in current session
HKLM:Hkey Local Machine Hive
HKCU:Hkey Current User Hive
Variable:Variables in the current session
WSMan:WinRM configuration / credentials
AD:Active Directory
Set-location HKLM:HKLM Registry hive
gci variable:Variables in current session
Importing, Exporting, Converting
Export-CliXMLImport-CliXML
ConvertTo-XMLConvertTo-HTML
Export-CSVImport-CSV
ConvertTo-CSVConvertFrom-CSV
Common Commands
Get-EventLogGet-WinEvent
Get-CimInstanceGet-Date
Start-SleepCompare-Object
Start-JobGet-Credential
Test-ConnectionNew-PSSession
Test-PathSplit-Path
Default Variables
$_, $PSItemCurrent pipeline object
$ArgsScript or function arguments
$ErrorErrors from commands
$True,$FalseBoolean value for true,false
$nullEmpty
$profileArray of profile locations
Help and Information
Update-HelpDownloads and installs newest help files
Get-HelpDisplays information about commands and concepts
Get-CommandGets all commands
Get-MemberGets the properties and methods of objects
Get-ModuleGets the modules that have been imported or that can be imported into the current session
Preference Variables
$ConfirmPreferenceDetermines whether Windows PowerShell automatically prompts you for confirmation before running a cmdlet or function
$DebugPreferenceDetermines how Windows PowerShell responds to debugging
$ErrorActionPreferenceDetermines how Windows PowerShell responds to a nonterminating error
$ErrorViewDetermines the display format of error messages in Windows PowerShell
$FormatEnumerationLimitDetermines how many enumerated items are included in a display
$MaximumHistoryCountDetermines how many commands are saved in the command history for the current session
$OFS Output Field Separator.Specifies the character that separates the elements of an array when the array is converted to a string. The default value is: Space.
$OutputEncodingDetermines the character encoding method that Windows PowerShell uses when it sends text to other applications
$PSDefaultParameterValuesSpecifies default values for the parameters of cmdlets and advanced functions
$PSEmailServerSpecifies the default e-mail server that is used to send e-mail messages
$PSModuleAutoLoadingPreferenceEnables and disables automatic importing of modules in the session. "All" is the default.
$PSSessionApplicationNameSpecifies the default application name for a remote command that uses WS-Management technology
$PSSessionConfigurationNameSpecifies the default session configuration that is used for PSSessions created in the current session
$PSSessionOptionEstablishes the default values for advanced user options in a remote session
$VerbosePreferenceDetermines how Windows PowerShell responds to verbose messages generated by a script, cmdlet or provider
$WarningPreferenceDetermines how Windows PowerShell responds to warning messages generated by a script, cmdlet or provider
$WhatIfPreferenceDetermines whether WhatIf is automatically enabled for every command that supports it
Helpful Microsoft Resources
Microsoft Windows PowerShellhttp://www.microsoft.com/powershell
Windows PowerShell Team Bloghttp://blogs.msdn.com/PowerShell
MS TechNet Script Centerhttp://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
PowerShell Forumhttp://social.technet.microsoft.com/Forums/en-US/winserverpowershell/
Hey, Scripting Guy! Bloghttp://blogs.technet.com/b/heyscriptingguy/
Windows PowerShell Survival Guidehttp://social.technet.microsoft.com/wiki/contents/articles/183.windows-powershellsurvival-guide-en-us.aspx
Active Directory - User Objects
Get-ADUser -Identity 'John Smith'View user account details
Get-ADUser -Filter 'Name -like "John Smith"'Search for a user
Get-ADUser -Filter * -SearchBase "OU=marketing,OU=Users,DC=domain,DC=local"Search for users in a particular OU
Get-ADUser -Identity 'JohnSmith' Properties Description,OfficeView additional properties, not just the default set
Get-ADUser -Identity 'JohnSmith' -Properties *View all the user properties, not just default set
New-ADUser -Name "John Smith" SamAccountName "JohnSmith" GivenName "John" -Surname "Smith" -DisplayName "John Smith" -Path 'OU=Users,OU=marketing,DC=domain,DC=local' -OtherAttributes @{'Title'="Marketing Manager"} AccountPassword (Read-Host AsSecureString "AccountPassword") -Enabled $trueCreate a new user
Set-ADUser John Smith -City London -Remove @{otherMailbox="John.Smith"} -Add @{url="domain.local"} -Replace @{title="manager"} -Clear descriptionChange the properties of a user
Active Directory - Computer Objects
Get-ADComputer -Filter 'Name like "Server01"'View computer account details
New-ADComputer -Name "Server01" SamAccountName "Server01" -Path "OU=Computers,OU=Resources,DC=tes t,DC=local" -Enabled $true Location "London"Create a new computer account
Remove-ADComputer -Identity "Server01" -Confirm:$falseRemove a computer account


About the Author

dwirch has posted a total of 188 articles.


Comments On This Post

No comments on this post yet!


Do you have a thought relating to this post? You can post your comment here. If you have an unrelated question, you can use the Q&A section to ask it.

Or you can drop a note to the administrators if you're not sure where you should post.


Your IP address is:54.167.29.208

Before you can post, you need to prove you are human. If you log in, this test goes away.




Code Links