POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

28
POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    0

Transcript of POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Page 1: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

POWERSHELL

Dr. Sarah Gothard

CEG 233

Spring 2010

Page 2: 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-executionpolicy remotesigned”.

Unsigned scripts that were downloaded must be individually unblocked in file properties from Windows Explorer.

Page 3: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 4: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 5: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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.

Page 6: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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.

Page 7: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Scalar Variables

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

Page 8: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

$?  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

Page 9: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

$OFSOutput 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.

$ShellIDThe 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

Page 10: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Escape Sequences

Escape Sequence

Description

`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

Page 11: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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}

Page 12: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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.

Page 13: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 14: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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.

Page 15: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 16: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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}

Page 17: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 18: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 19: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 20: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Comparison Operators

Operation Operator

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

Page 21: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Text Comparison Operators

Operation Operator

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

Page 22: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Branch Statements

if (condition) {code block}elseif (condition) {code block}else {code block}

switch (expression){

(test) {code block} value {code block} default {code block}}

Page 23: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 24: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Functions

Creationfunction name{ param($param1, $param2) operations}

Invocationfunction_name arg1 arg2

Page 25: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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.

Page 26: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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

Page 27: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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()

Page 28: POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

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