290 likes | 551 Views
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.wright.edu:2048/9781932394500
E N D
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.wright.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-executionpolicyremotesigned”. • 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 regexsupport • 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 PowerShellcmdlet, 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
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: • 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: rmor 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-Servicepattern • Get-Service | Where-Object {$_.Status -eq "Stopped"} • Process by name • Get-Process -Namepattern • Get-Process | Sort-Object cpu| select-object -last 5 • Variable by name: Get-Variable -Namepattern
Compare File Contents • diff-referenceobject $(get-content reference file) -differenceobject $(get-content compare file) • diff -referenceobject $(get-content reference file) -differenceobject $(get-content 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
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 semicolon-separated statements): $() • Array Subexpression: @()
Create Windows Shortcut • $wsh = New-Object -ComObjectWScript.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