<<

Windows PowerShell 3.0 Language Quick Reference Created by http://powershellmagazine.com

Useful Commands Bitwise Operators , Comma operator (Array - Bitwise AND ) Update- Downloads and installs newest help -bor Bitwise OR (inclusive) . Dot-sourcing operator runs a files -bxor Bitwise OR (exclusive) script in the current Get-Help Displays information about -bnot Bitwise NOT . ="">c:\scripts\sample.ps1 commands and concepts -shl, -shr Bitwise shift operators. Bit Get- 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-" -join Joins multiple strings & $a Assignment Operators “abc”,”def”,”ghi” -join “;” $sb = { Get-Process | Select –First 2 } =, +=, -=, *=, /=, %=, ++, -- Assigns one or values & $sb to a variable .. Range operator Logical Operators 1..10 | foreach {$_ * 5} Comparison Operators -and, -or, -xor, -not, ! Connect expressions and -eq, -ne Equal, not equal statements, allowing you to test -is, -isnot Type evaluator (Boolean). -gt, -ge Greater than, greater than for multiple conditions Tells whether an object is an or equal to Redirection Operators instance of a specified . -lt, -le than, less than or >, >> The redirection operators enable . equal to you to send particular types of 42 –is [int] - changes the specified output (, error, warning, elements of a value verbose, and ) to files and -as Type convertor. Tries to “” -replace “bc”, “TEST” to the success output stream. the input object to Output streams * All output the specified .NET -match, -notmatch Regular expression match 1 Success output Framework type. -like, -notlike Wildcard matching 2 Errors $a = 42 –as [String] -contains, -notcontains Returns TRUE if the scalar 3 Warning messages value on its right is 4 Verbose output -f Formats strings by using the contained in the array on 5 Debug messages method of string its left # Writes warning output to warning.txt objects 1,2,3,4,5 -contains 3 Do-Something 3> warning.txt 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 test value exactly matches # Writes debug output to the output stream limits objects to the least one of the Do-Something 5>&1 specified type reference values. # Redirects all streams to out.txt [datetime]$birthday = "1/10/66" “Windows”-in “Windows”,”PowerShell” Do-Something *> out.txt Windows PowerShell 3.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 Static methods are callable with the "::" operator. @() Empty array [pscustomobject]@{=1; y=2} Creates a custom @(2) Array of one 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 $arr[1,4+6..9] Displays the elements at carriage returns and quotes. Expressions are evaluated: index positions 1,4, and 6 Write-Host Hello#world $(2+2*5). Note that the end marker of the here-string must through 9 be at the beginning of a ! @(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 object’s properties can be referenced directly with the (increases the value of the Variables "." operator. element) Format: $[scope:]name or ${anyname} or ${any } $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()} $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 and with -Job $hash = @{} Creates empty hash table Methods $localVar = Read-Host ", please" @{foo=1; bar='value2'} Creates and initialize a Methods can be called on objects. Invoke-Command -ComputerName localhost -ScriptBlock { hash table $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 += ";:\Scripts" $hash.key1 = 1 Assigns 1 to key key1 $a.ToUpper() Windows PowerShell 3.0 Language Quick Reference Created by http://powershellmagazine.com

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

Windows PowerShell Learning Resources The PowerShell Community Toolbar http://powershell.ourtoolbar.com/ Resources irc.freenode.net #PowerShell PowerShell http://www.microsoft.com/powershell Free eBooks and Guides Windows PowerShell Team Blog http://blogs.msdn.com/PowerShell Mastering PowerShell, Second Edition - Dr. Tobias Weltner http://powershell.com/cs/blogs/ebookv2/default.aspx MS TechNet Script Center http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx Secrets of PowerShell Remoting - Don Jones and Dr. Tobias Weltner http://powershellbooks.com PowerShell Forum http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/ Administrator's Guide to Windows PowerShell Remoting Dr. Tobias Weltner, Aleksandar Nikolic, Richard Giles Hey, Scripting Guy! Blog http://powershell.com/cs/media/p/4908.aspx http://blogs.technet.com/b/heyscriptingguy/ Layman's Guide to PowerShell 2.0 Remoting - Ravikanth Chaganti Windows PowerShell Survival Guide http://www.ravichaganti.com/blog/?page_id=1301 http://social.technet.microsoft.com/wiki/contents/articles/183.windows-powershell- survival-guide-en-us.aspx WMI Query Language via PowerShell - Ravikanth Chaganti http://www.ravichaganti.com/blog/?page_id=2134 Community Resources PowerShell 2.0 One Cmdlet at a Time - Jonathan Medd PowerShell Community http://www.jonathanmedd.net/2010/09/powershell-2-0-one-cmdlet-at-a--available- http://powershellcommunity.org as-pdf-download.html

PowerShell Code Repository Effective Windows PowerShell - Keith Hill http://poshcode.org http://rkeithhill.wordpress.com/2009/03/08/effective-windows-powershell-the-free- ebook/ PowerShell.com Community http://powershell.com

PowerGUI.org Community Books http://powergui.org Don Jones, Learn Windows PowerShell in a Month of Lunches PowerShell Community Groups Bruce Payette, Windows PowerShell in Action, Second Edition http://powershellgroup.org Lee Holmes, Windows PowerShell Cookbook, Second Edition PowerShell Magazine http://powershellmagazine.com