POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010 Reference Book Suggestion Windows PowerShell in Action by Bruce Payette (co-designer of the PowerShell language) is available online at http://proquest.safaribooksonline.com.ezproxy.libraries.wrig ht.edu:2048/9781932394500 That same site has about 10 other PowerShell books Posted examples from Windows PowerShell in Action: http://www.manning.com/payette/ To run a script for the first time, you must open PowerShell in administrator mode (right click on the shortcut and choose “run as Administrator) and type “set-executionpolicy remotesigned”. Unsigned scripts that were downloaded must be individually unblocked in file properties from Windows Explorer. PowerShell Introduction object based—everything in PowerShell is an object built on MS .NET framework can access any .NET object output is always a .NET object many common Linux commands work in PowerShell full regex support unless explicitly stated, nothing is case sensitive PowerShell is technically strongly typed but performs automatic type conversions as needed scripts are not associated directly with the shell for security Handy starting commands Help: man or Get-Help man * man about_* man –detailed man -full Command list: gcm or Get-Command Variable list: gv or Get-Variable Drive information: gdr or Get-PSDrive Run a cmd command: cmd /c target_command Interface Operations To freeze the screen, highlight any text. To copy text, highlight it and press enter. To paste text, right click in the PowerShell window. Use home and end to go to the beginning and the end of a line, respectively. Use up and down arrows to navigate command history. Use pg up to see the first command entered in a session and pg dn to see the last. Scripting and Command Line Any PowerShell cmdlet, control statement, operation, etc., can be used both in a script and from the command line. If a typed command is clearly not finished, PowerShell will begin a new console line after the first. Once the code is complete, hit enter twice to trigger completion. To type something from the command line that requires an extra line, put a backquote at the end of the first line. Hit enter twice when you are done. Scalar Variables $num = 1 $str = "Hi" $flt = [Math]::Pi $proc = (get-process)[0] $date = Get-Date Provided Variables (part 1) Name $_ Description The current pipeline object; used in script blocks, filters, the process clause of functions, where-object, foreach-object and switch $^ contains the first token of the last line input into the shell $$ contains the last token of last line input into the shell $? $Args Contains the success/fail status of the last statement Used in creating functions that require parameters If an error occurred, the object is saved in the $error PowerShell $Error variable $foreach Refers to the enumerator in a foreach loop. $HOME The user's home directory; set to %HOMEDRIVE%\%HOMEPATH% $Host Information about the currently executing host $Input Input piped to a function or code block Provided Variables (part 2) Name Description $LastExitCode The exit code of the last native application to run $Match A hash table consisting of items found by the –match operator. $MyInvocation Information about the currently script or command-line $true Boolean TRUE $false Boolean FALSE $null A null object Output Field Separator, used when converting an array to a $OFS string. By default, this is set to the space character. $profile Path to a script file that will execute each time PS is opened. The identifier for the shell. This value is used by the shell to $ShellID determine the ExecutionPolicy and what profiles are run at startup. $StackTrace contains detailed stack trace information about the last error Escape Sequences Escape Sequence `a `` `b `r `$ `n `0 `” `’ `t ` Description Alert Back quotation Backspace Carriage return Dollar sign Line feed Null Quotation mark Single quotation mark Tab Continue to next line Math and Time System.Math All typical math operations Use with get-member -static System.DateTime Use with get-member -static Get-Random Timing a command: Measure-Command {target command} Collections Any variable can be treated like a collection of one. collections are zero based Collections are automatically flattened when they are sent down a pipe To keep collections from being flattened, use a comma before the collection. The unary comma operator instructs PowerShell to wrap the object in a new array that contains that single object. When that array is flattened, we get our original array. Collection Examples $nums = 1, 2, 3+7..20 $strs = “Hi”, “Mom” $flts = [Math]::Pi, [Math]::E $procs = Get-Process $files = @(Get-ChildItem *.sys) @ forces a collection Empty Sets Valid output can consist of an empty set $null is used to represent an empty set The foreach statement iterates over a scalar once, even if that scalar happens to be $null. Aliases Most PowerShell commands have a shorter alias. Operations: List the current aliases: get-alias Find aliases for a given command: get-alias -def command Find command for a given alias: get-alias alias Create an alias: set-alias name target To load a set of aliases each time, put them in your profile file, whose path is stored in the variable $PROFILE: 1. 2. Create your profile file manually: ni -path $profile -itemtype file -force Open your file: notepad $profile Files Get with Get-Item or Get-ChildItem Call methods on files: (Get-item books.txt).isReadOnly = $true (gi books.txt).set_isReadOnly($true) Create file: ni or New-Item Remove file: rm or Remove-Item Check if a file exists: Test-Path Check if directory: Get-Item * | where {$_.PSISContainer} Search File by name Get-Item -path path -filter pattern Get-Childitem -recurse -path path -filter pattern File contents Select-String –path path –pattern pattern Get-Childitem -recurse * | select-string -pattern pattern Service by name: Get-Service pattern Get-Service | Where-Object {$_.Status -eq "Stopped"} Process by name Get-Process -Name pattern Get-Process | Sort-Object cpu | select-object -last 5 Variable by name: Get-Variable -Name pattern Compare File Contents diff -referenceobject $(get-content reference file) -differenceobject $(getcontent compare file) diff -referenceobject $(get-content reference file) -differenceobject $(getcontent compare file) –includeequal Midline cmdlets Midline cmdlets are cmdlets that normally operate on operands that are piped to them. Examples: where-object: get-service | Where-Object {$_.Status –eq “Stopped”} more foreach Sort-Object Select-String Get-Member Comparison Operators Operation Equal to Less than Greater than Greater than or equal to Less than or equal to Not equal to Not And Or Operator -eq -lt -gt -ge -le -ne -not, ! -and -or Text Comparison Operators Operation Like Not like Match Not Match Replace Equal Not equal Case-sensitive equal Case-sensitive not equal Operator -like -notlike -match -notmatch -replace -eq -ne -ceq -cne Branch Statements if (condition) {code block} elseif (condition) {code block} else {code block} switch (expression) { (test) {code block} value {code block} default {code block} } Loops do { code block } while (condition) while (condition) { code block } do { code block } until (condition) for (init; condition; increment) { code block } foreach ($var in $array) { code block } break continue Functions Creation function name { param($param1, $param2) operations } Invocation function_name arg1 arg2 Function returns A return statement essentially ends the method. Any function output that wasn’t captured is returned. To keep from returning more than you intend, throw away unwanted output: [void]$string.append ($i) mkdir folder 2> $null Output from an echo is considered a return value. If you want it to output to the screen instead, use Write-Host. Parsing Modes Strings do not need quotes unless they have spaces & in front forces a string to be executed A dot in front executes a script Expression: () Subexpression (possibility of multiple semicolonseparated statements): $() Array Subexpression: @() Create Windows Shortcut 1. 2. 3. 4. $wsh = New-Object -ComObject WScript.Shell $link = $wsh.CreateShortcut(“absolute path to shortcut\shortcut name.lnk”) $link.TargetPath = “absolute path of file” $link.Save() Advanced Topics (see reference book) Output text colors Errors and exceptions Built-in debugging GUI scripts (several examples in reference book) Windows system administration: WMI Security Provided Windows PowerShell ISE