You are on page 1of 4

WINDOWS POWERSHELL 4.

0 LANGUAGE QUICK REFERENCE


Created by http://powershellmagazine.com

Useful Commands Bitwise Operators , Comma operator (Array


-band Bitwise AND constructor)
Update-Help Downloads and installs newest help -bor Bitwise OR (inclusive) . Dot-sourcing operator runs a
files -bxor Bitwise OR (exclusive) script in the current scope
Get-Help Displays information about -bnot Bitwise NOT . c:\scripts\sample.ps1
commands and concepts -shl, -shr Bitwise shift operators. Bit
Get-Command Gets all commands shift left, bit shift right $( ) Subexpression operator
Get-Member Gets the properties and methods (arithmetic for signed, @( ) Array subexpression operator
of objects logical for unsigned values) & The call operator, also known as
Get-Module Gets the modules that have been the "invocation operator," lets
imported or that can be imported Other Operators you run commands that are
into the current session -Split Splits a string stored in variables and
abcdefghi -split de represented by strings.
Operators $a = "Get-Process"
-join Joins multiple strings & $a
Assignment Operators $sb = { Get-Process | Select First 2 }
abc,def,ghi -join ;
=, +=, -=, *=, /=, %=, ++, -- Assigns one or more values & $sb
to a variable
.. Range operator Logical Operators
1..10 | foreach {$_ * 5} -and, -or, -xor, -not, ! Connect expressions and
Comparison Operators
-eq, -ne Equal, not equal statements, allowing you to test
-is, -isnot Type evaluator (Boolean). for multiple conditions
-gt, -ge Greater than, greater than
Tells whether an object is an Redirection Operators
or equal to
instance of a specified .NET >, >> The redirection operators enable
-lt, -le Less than, less than or
Framework type. you to send particular types of
equal to
42 is [int] output (success, error, warning,
-replace changes the specified
elements of a value verbose, and debug) to files and
-as Type convertor. Tries to to the success output stream.
abcde -replace bc, TEST
convert the input object to Output streams * All output
the specified .NET 1 Success output
-match, -notmatch Regular expression match
Framework type. 2 Errors
-like, -notlike Wildcard matching
$a = 42 as [String] 3 Warning messages
-contains, -notcontains Returns TRUE if the scalar
value on its right is 4 Verbose output
-f Formats strings by using the 5 Debug messages
contained in the array on
format method of string # Writes warning output to warning.txt
its left
objects Do-Something 3> warning.txt
1,2,3,4,5 -contains 3
1..10 | foreach { "{0:N2}" -f $_ } # Appends verbose.txt with the verbose output
-in, -notin Returns TRUE only when Do-Something 4>> verbose.txt
[] Cast operator. Converts or # Writes debug output to the output stream
test value exactly matches
limits objects to the Do-Something 5>&1
at least one of the
specified type # Redirects all streams to out.txt
reference values.
[datetime]$birthday = "1/10/66" Do-Something *> out.txt
Windows-in Windows,PowerShell
WINDOWS POWERSHELL 4.0 LANGUAGE QUICK REFERENCE
Created by http://powershellmagazine.com

Arrays $hash.key1 Returns value of key1 $a.Substring(0,3)


$hash["key1"] Returns value of key1 $a | Get-Member -MemberType Method -Static
"a", "b", "c" Array of strings $hash.GetEnumerator | sort Key Sorts a hash table by
1,2,3 Array of integers the Key property Static methods are callable with the "::" operator.
@() Empty array [pscustomobject]@{x=1; y=2} Creates a custom
@(2) Array of one element object [DateTime]::IsLeapYear(2012)
1,(2,3),4 Array within array
,"hi" Array of one element Comments Strings
$arr[5] Sixth element of array*
$arr[2..20] Returns elements 3 thru 21 # This is a comment because # is the first character of a "This is a string, this $variable is expanded as is $(2+2)"
$arr[-1] Returns the last array token This is a string, this $variable is not expanded
element
$arr[-3..-1] Displays the last three $a = "#This is not a comment" @"
elements of the array $a = "something" # but this is. This is a here-string can contain anything including carriage
$arr[1,4+6..9] Displays the elements at returns and quotes. Expressions are evaluated: $(2+2*5).
index positions 1,4, and 6 Write-Host Hello#world Note that the end marker of the here-string must be at the
through 9 beginning of a line!
@(Get-Process) Forces the result to an Block Comments "@
array using the array sub-
expression operator <# This is @'
$arr=1..10 A multi-line comment #> Here-strings with single quotes do not evaluate expressions:
$arr[($arr.length-1)..0] Reverses an array $(2+2*5)
$arr[1] += 200 Adds to an existing value of Object Properties '@
the second array item
An objects properties can be referenced directly with the Variables
(increases the value of the
"." operator.
element) Format: $[scope:]name or ${anyname} or ${any path}
$b = $arr[0,1 + 3..6] Creates a new array based $a = Get-Date
on selected elements of an $a | Get-Member MemberType Property $path = "C:\Windows\System32"
existing array $a.Date Get-ChildItem ${env:ProgramFiles(x86)}
$z = $arr + $b Combines two arrays into a $a.TimeOfDay.Hours $processes = Get-Process
single array, use the plus $a | Get-Member -MemberType Property Static
operator (+) $global:a =1 # visible everywhere
Static properties can be referenced with the "::" operator. $local:a = 1 # defined in this scope and visible to children
*Arrays are zero-based $private:a = 1 # same as local but invisible to child scopes
[DateTime]::Now $script:a = 1 # visible to everything is this script
Associative Arrays (Hash tables) # Using scope indicates a local variable in remote commands
Methods and with Start-Job
$hash = @{} Creates empty hash table
$localVar = Read-Host "Directory, please"
@{foo=1; bar='value2'} Creates and initialize a
Methods can be called on objects. Invoke-Command -ComputerName localhost -ScriptBlock {
hash table
dir $using:localVar }
[ordered]@{a=1; b=2; c=3}Creates an ordered $a = "This is a string" Start-Job { dir $using:localVar -Recurse}
dictionary $a | Get-Member MemberType Method $env:Path += ";D:\Scripts"
$hash.key1 = 1 Assigns 1 to key key1 $a.ToUpper()
WINDOWS POWERSHELL 4.0 LANGUAGE QUICK REFERENCE
Created by http://powershellmagazine.com

Get-Command -Noun Variable # the Variable Cmdlets $Input Enumerator of objects piped to a script $OFS Output Field Separator. Specifies
Get-ChildItem variable: # listing all variables using the $LastExitCode Exit code of last program or script the character that separates the
variable drive $Matches Stores a hash table of string values elements of an array when the
matched by the -match or -notmatch array is converted to a string. The
# strongly-typed variable (can contain only integers) comparison operators. default value is Space.
[int]$number=8 $MyInvocation An object with information about the $PSDefaultParameterValues Specifies default values for the
current command parameters of cmdlets and
# attributes can be used on variables $PSHome The installation location of Windows advanced functions
[ValidateRange(1,10)][int]$number = 1 PowerShell $PSModuleAutoLoadingPreference Enables and disables
$number = 11 #returns an error $profile The standard profile (may not be automatic importing of modules
present) in the session. "All" is the default.
# flip variables $Switch Enumerator in a switch statement $PSSessionApplicationName Specifies the default application
$a=1;$b=2; $a,$b = $b,$a $True Boolean value for TRUE name for a remote command that
$False Boolean value for FALSE uses WS-Management technology
# multi assignment $PSCulture Current culture $PSSessionConfigurationName Specifies the default session
$a,$b,$c = 0 $PSUICulture Current UI culture configuration that is used for
$a,$b,$c = 'a','b','c' $PsVersionTable Details about the version of Windows PSSessions created in the current
$a,$b,$c = 'a b c'.split() PowerShell session
$Pwd The full path of the current directory $PSSessionOption Establishes the default values for
# create read only variable (can be overwritten with - advanced user options in a
Force) Windows PowerShell Preference Variables remote session
Set-Variable -Name ReadOnlyVar -Value 3 -Option (not exhaustive) $VerbosePreference Determines how Windows
ReadOnly $ConfirmPreference Determines whether Windows PowerShell responds to verbose
PowerShell automatically messages generated by a script,
# create Constant variable (cannot be overwritten) prompts you for confirmation cmdlet or provider
Set-Variable -Name Pi -Value 3.14 -Option Constant before running a cmdlet or $WarningPreference Determines how Windows
function PowerShell responds to warning
Windows PowerShell Automatic Variables $DebugPreference Determines how Windows messages generated by a script,
(not exhaustive) PowerShell responds to cmdlet or provider
$$ Last token of the previous debugging $WhatIfPreference Determines whether WhatIf is
command line $ErrorActionPreference Determines how Windows automatically enabled for every
$? Boolean status of last command PowerShell responds to a non- command that supports it
$^ First token of the previous terminating error Collection Filtering
command line $FormatEnumerationLimitDetermines how many
$_, $PSItem Current pipeline object enumerated items are included Collection filtering by using a method syntax is supported.
$Args Arguments to a script or function in a display .Where({ expression } [, mode [, numberToReturn]])
$Error Array of errors from previous $MaximumHistoryCount Determines how many .ForEach({ expression } [, arguments...])
commands commands are saved in the
$ForEach Reference to the enumerator in a command history for the $Services = Get-Service
foreach loop current session $Services.Where({$_.Status -eq Stopped}, 'First', 3)
$Home The users home directory $PSEmailServer Specifies the default e-mail $Services.ForEach{$_.Name.ToUpper()}
$Host Reference to the application server that is used to send e-
hosting the PowerShell language mail messages (1..5).ForEach({$args[0] + $_},'Server')
WINDOWS POWERSHELL 4.0 LANGUAGE QUICK REFERENCE
Created by http://powershellmagazine.com

WINDOWS POWERSHELL LEARNING RESOURCES The PowerShell Community Toolbar: http://powershell.ourtoolbar.com/

Microsoft Resources PowerScripting Podcast: http://powerscripting.net

Scripting with Windows PowerShell PowerShell Magazine: http://powershellmagazine.com


http://technet.microsoft.com/library/bb978526.aspx
irc.freenode.net #PowerShell
Windows PowerShell Team Blog
http://blogs.msdn.com/PowerShell Free eBooks and Guides

Microsoft Script Center Mastering PowerShell, Second Edition - Dr. Tobias Weltner
http://technet.microsoft.com/scriptcenter/default http://powershell.com/cs/blogs/ebookv2/default.aspx

Windows PowerShell Forum PowerShell.org Free eBooks
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/ http://powershell.org/wp/ebooks/

Hey, Scripting Guy! Blog Effective Windows PowerShell - Keith Hill
http://blogs.technet.com/b/heyscriptingguy/ http://rkeithhill.wordpress.com/2009/03/08/effective-windows-powershell-the-free-
ebook/
Windows PowerShell Survival Guide
http://social.technet.microsoft.com/wiki/contents/articles/183.windows-powershell- Popular Community Projects
survival-guide-en-us.aspx
PowerShell Community Extensions (PSCX)
Windows PowerShell ISE Add-on Tools http://pscx.codeplex.com/
http://social.technet.microsoft.com/wiki/contents/articles/2969.windows-powershell-
ise-add-on-tools.aspx PSReadLine - A bash inspired readline implementation for PowerShell
https://github.com/lzybkr/PSReadLine
Windows PowerShell Customer Connection: Submit bugs and feature requests
https://connect.microsoft.com/powershell TabExpansionPlusPlus - PowerShell module to improve tab expansion and Intellisense
https://github.com/lzybkr/TabExpansionPlusPlus
Report Windows PowerShell documentation bugs by email
write-help@microsoft.com PowerSploit - A PowerShell Post-Exploitation Framework
https://github.com/mattifestation/PowerSploit

Community Resources PoshSec - PowerShell module focused on security in the Windows environment
https://github.com/PoshSec/PoshSec
PowerShell Code Repository: http://poshcode.org
Posh-SecMod - PowerShell module with security-related cmdlets
PowerShell.com Community: http://powershell.com
https://github.com/darkoperator/Posh-SecMod
PowerShell.org Community: http://powershell.org
Pester - PowerShell BDD-style testing framework
https://github.com/pester/Pester
PowerGUI Community: http://en.community.dell.com/techcenter/powergui/

You might also like