WINDOWS POWERSHELL 4.0 LANGUAGE QUICK REFERENCE Created By
Total Page:16
File Type:pdf, Size:1020Kb
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 “abc”,”def”,”ghi” -join “;” $sb = { Get-Process | Select –First 2 } =, +=, -=, *=, /=, %=, ++, -- Assigns one or more 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 .NET -lt, -le Less than, less than or >, >> The redirection operators enable Framework type. equal to you to send particular types of 42 –is [int] -replace changes the specified output (success, error, warning, elements of a value verbose, and debug) to files and -as Type convertor. Tries to “abcde” -replace “bc”, “TEST” to the success output stream. convert 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 format 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 at 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 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 object’s properties can be referenced directly with the (increases the value of the Variables "." 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 and with Start-Job $hash = @{} Creates empty hash table Methods $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