Presentation is loading. Please wait.

Presentation is loading. Please wait.

POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Similar presentations


Presentation on theme: "POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010."— Presentation transcript:

1 POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010

2 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 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/ 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.

3 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

4 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

5 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.

6 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.

7 Scalar Variables  $num = 1  $str = "Hi"  $flt = [Math]::Pi  $proc = (get-process)[0]  $date = Get-Date

8 Provided Variables (part 1) NameDescription $_ 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 $? Contains the success/fail status of the last statement $Args Used in creating functions that require parameters $Error If an error occurred, the object is saved in the $error PowerShell 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

9 Provided Variables (part 2) NameDescription $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 $OFS Output Field Separator, used when converting an array to a string. By default, this is set to the space character. $profile Path to a script file that will execute each time PS is opened. $ShellID The identifier for the shell. This value is used by the shell to determine the ExecutionPolicy and what profiles are run at startup. $StackTrace contains detailed stack trace information about the last error

10 Escape Sequences Escape SequenceDescription `a Alert `` Back quotation `b Backspace `r Carriage return `$ Dollar sign `n Line feed `0 Null `” Quotation mark `’ Single quotation mark `t Tab ` Continue to next line

11 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}

12 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.

13 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

14 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.

15 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. Create your profile file manually: ni -path $profile -itemtype file -force 2. Open your file: notepad $profile

16 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}

17 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

18 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

19 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

20 Comparison Operators OperationOperator Equal to -eq Less than -lt Greater than -gt Greater than or equal to -ge Less than or equal to -le Not equal to -ne Not -not, ! And -and Or -or

21 Text Comparison Operators OperationOperator Like -like Not like -notlike Match -match Not Match -notmatch Replace -replace Equal -eq Not equal -ne Case-sensitive equal -ceq Case-sensitive not equal -cne

22 Branch Statements if ( condition ) { code block } elseif ( condition ) { code block } else { code block } switch ( expression ) { ( test ) { code block } value { code block } default { code block } }

23 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

24 Functions  Creation function name { param($param1, $param2) operations }  Invocation function_name arg1 arg2

25 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.

26 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: @()

27 Create Windows Shortcut 1. $wsh = New-Object -ComObject WScript.Shell 2. $link = $wsh.CreateShortcut(“ absolute path to shortcut\shortcut name.lnk”) 3. $link.TargetPath = “ absolute path of file ” 4. $link.Save()

28 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


Download ppt "POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010."

Similar presentations


Ads by Google