PowerShell Tutorial - Hig.no

Transcription

PowerShellEigil Obrestadand and-line argsInputPowerShell TutorialInputSystem commandsConditionsif/elseOperatorsEigil Obrestad and Erik athFunctionsRegExpPowerShell examplePowerShellonlyCreditsAugust 18, 2015

PowerShellEigil Obrestadand and-line argsInputInputSystem ell examplePowerShellonlyCredits(OUSTERHOUT, J., “Scripting: Higher-Level Programming for the 21st Century”,IEEE Computer, Vol. 31, No. 3, March 1998, pp. 23-30.)

PowerShellEigil Obrestadand ssesCommand-line argsInputInputSystem The following presentation is NOT meant to be acomprehensive/complete tour of the PowerShell language.The purpose is to get you started with some basic programconstructions which you will recognize based WhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsAt the end of the presentation (Credits section) you will findpointers to more comprehensive material (referencematerial).

PowerShellEigil Obrestadand ssesCommand-line argsInputInputSystem commandsConditionsif/elseOperatorsSwitch/caseYou need a Windows host running on a physical or virtualmachine with working access to the internet, and withPowerShell v2.0 installed.Log in and open a terminal window, download the examplesas we go along fromWhereIterationhttp :// www . ansatt . hig . no / erikh / tutorial-powershell / FILForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits(or download all at once with filenamepowershell-examples.zip but remember to unblock beforeunzip)

PowerShellHello WorldEigil Obrestadand ErikHjelmåsVariablesArrays# hello . ps1Structures/ClassesCommand-line argsInputWrite-Host " hello world ! "InputSystem commandsConditionsexecute as long as filename ends with .ps1:if/elseOperatorsSwitch/case.\ hello . ps1WhereIterationForWhileForeachor direct from command line cmd (DOSPROMPT)powershell - command " Write-Host \ " hello world !\ " "MathFunctionsRegExpPowerShell examplePowerShellonlyCreditsor direct from command line powershellWrite-Host " hello world ! "

PowerShellSingle VariablesEigil Obrestadand and-line argsInput# single-var . ps1InputSystem Iteration firstname " Mysil " lastname " Bergsprekken " fullname " firstname lastname "Write-Host " Hello fullname , may I call you " " firstname ? "ForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsAll variables are prefixed with

PowerShellExerciseEigil Obrestadand and-line argsInputInputSystem commands name " Mysil onForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits Use the properties and methods of this object to find out how many characters the string contains print the string in upper case

PowerShellSingle and Double QuotesEigil Obrestadand and-line argsInputInputSystem ell examplePowerShellonlyCredits# quotes . ps1 name " Mysil "Write-Host HelloWrite-Host " HelloWrite-Host ' Hello name name " name '

PowerShellArraysEigil Obrestadand and-line argsOne-dimensional arrays:InputInputSystem IterationForWhile# array . ps1 os @ ( " linux " , " windows " ) os @ ( " mac " )Write-Host os [1]# print windowsWrite-Host os# print array valuesWrite-Host os . Count # length of arrayForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsArrays are created with @(.)

PowerShellAssociative ArraysEigil Obrestadand ErikHjelmåsVariablesArraysStructures/Classes# assoc-array . ps1Command-line argsInputInputSystem IterationForWhileForeach user @ {" frodeh " " Frode Haug " ;" ivarm " " Ivar Moe "} user @ { " lailas " " Laila Skiaker " }Write-Host user [ " ivarm " ] # printWrite-Host @user# printWrite-Host user . Keys# printWrite-Host user . Count# printIvar Moearray valuesarray keyslength of arrayMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsAssociative arrays are created with @{.} and are calledHashtables in PowerShell.

PowerShellStructures/ClassesEigil Obrestadand ErikHjelmåsVariablesArraysStructures/ClassesA simple object used as a struct:# struct . ps1Command-line argsInputInputSystem ell examplePowerShellonlyCredits myhost New-Object PSObject - Property @ { os " " ;sw @ ();user @ {}} myhost . os " linux " myhost . sw @ ( " gcc " ," flex " ," vim " ) myhost . user @ {" frodeh " " Frode Haug " ;" monicas " " Monica Strand "}Write-Host myhost . osWrite-Host myhost . sw [2]Write-Host myhost . user [ " monicas " ]

PowerShellEigil Obrestadand ErikHjelmåsCommand-Line line argsInputInputSystem commandsConditionsif/elseOperatorsAll command-line arguments in the array argsScriptname retrieved from the object MyInvocation# cli-args . ctionsRegExpPowerShell examplePowerShellonlyCreditsWrite-Host " I am " MyInvocation . InvocationName " and have " args . Count " arguments " " first is " args [0]

PowerShellEigil Obrestadand ssesCommand-line argsInputInputSystem ell examplePowerShellonlyCredits Rewrite the previous script to only have one string (justone set of double quotes (")), one at the beginning andone at the end, do not use single quotes either

PowerShellInput From UserEigil Obrestadand and-line argsInputInputSystem commands# input-user . tionForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits something Read-Host " Say something here "Write-Host " you said " something

PowerShellInput From the PipelineEigil Obrestadand and-line argsInputInput# input-pipe . ps1System commandsConditionsif/elseOperators something " input "Write-Host " you said " somethingSwitch/caseWhereIterationcan be executed asForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsWrite-Output " hey hey ! " .\ input-pipe . ps1

PowerShellInput From FilesEigil Obrestadand and-line argsInputInputSystem commands# input-file . tionForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits file Get-Content hello . ps1Write-Host @file - Separator " n "

PowerShellEigil Obrestadand ErikHjelmåsInput from System ine argsInputInput# input-commands . ps1System ell examplePowerShellonlyCredits name ( Get-WmiObject W in32 Oper atin gSyst em ). Name kernel ( Get-WmiObject W i n 32 O perat ingS yste m ). VersionWrite-Host " I am running on name , version " " kernel in ( Get-Location ) "

PowerShellif/elseEigil Obrestadand and-line argsInputInput# if . ps1System ell examplePowerShellonlyCreditsif ( args . Length - ne 1) {Write-Host " usage : " MyInvocation . InvocationName " argument "}

PowerShellComparisonEigil Obrestadand and-line argsInputInputSystem ell examplePowerShellonlyCreditsOperator lt gt le ge eq neMeaningLess thanGreater thanLess than or equal toGreater than or equal toEqual toNot equal to

PowerShellBooleanEigil Obrestadand and-line argsInputInputSystem ell examplePowerShellonlyCreditsOperator not! and orMeaningNotNotAndOr

PowerShellEigil Obrestadand and-line argsInputInputSystem ell examplePowerShellonlyCredits# if-num-string . ps1if ( args . Count - ne 2) {Write-Host " usage : " MyInvocation . InvocationName " argument argument "exit 0} elseif ( args [0] - gt args [1]) {Write-Host args [0] " larger than " args [1]} else {Write-Host args [0] " smaller than or " " equal to " args [1]}if ( Test-Path args [0]) {if (!( Get-Item args [0]). PSIsContainer ) {Write-Host args [0] " is a file "}}

PowerShellBoolean exampleEigil Obrestadand ErikHjelmåsVariablesArrays# if-bool . ps1Structures/ClassesCommand-line argsInputInputSystem commandsConditionsif/elseOperatorsif ((1 - eq 2) - and (1 - eq 1) - or (1 - eq 1)) {Write-Host " And has precedence "} else {Write-Host " Or has precedence "}Switch/caseWhere# force OR precedence hell examplePowerShellonlyCreditsif ((1 - eq 2) - and ((1 - eq 1) - or (1 - eq 1))) {Write-Host " And has precedence "} else {Write-Host " Or has precedence "}

PowerShellSwitch/CaseEigil Obrestadand and-line args# switch . ps1InputInputSystem ell examplePowerShellonlyCredits short @ { yes " y " ; nope " n " } ans Read-Hostswitch ( ans ) {yes { Write-Host " yes " }nope { Write-Host " nope " ; break }{ short . ContainsKey ( " ans " )} { Write-Host short [ ans ] }default { Write-Host " ans ? " }}

PowerShellWhere/Where-ObjectEigil Obrestadand and-line argsInputInputSystem commandsConditions# where . leForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsGet-ChildItem Where-Object { . Length - gt 1 KB }

PowerShellEigil Obrestadand ssesCommand-line argsInputInputSystem ell examplePowerShellonlyCredits Use Get-Process and Where-Object to list all powershell processes store the process table in an array procs list all processes with a working set greater than10MB

PowerShellFor loopEigil Obrestadand ErikHjelmåsVariables# for . ps1ArraysStructures/ClassesCommand-line argsInputInputSystem commandsConditionsif/elsefor ( i 1; i-le3 ; i ) {Write-Host " i "}# something more useful MathFunctionsRegExpPowerShell examplePowerShellonlyCredits file Get-ChildItemfor ( i 0; i-lt file . Count ; i ) {if (!( Get-Item file [ i ]). PSIsContainer ) {Write-Host file [ i ]. Name " is a file "} else {Write-Host file [ i ]. Name " is a directory "}}

PowerShellEigil Obrestadand and-line argsInputInputSystem commandsConditionsif/elseWhile# while . ps1while ( i - le 3) {Write-Host i i }# something more useful MathFunctionsRegExpPowerShell examplePowerShellonlyCredits file Get-ChildItem i 0while ( i - lt file . Count ) {if (!( Get-Item file [ i ]). PSIsContainer ) {Write-Host file [ i ]. Name " is a file "} else {Write-Host file [ i ]. Name " is a directory "} i }

PowerShellForeach loopEigil Obrestadand ErikHjelmåsVariables# foreach . ps1ArraysStructures/ClassesCommand-line argsInputInputSystem commandsConditionsif/elseforeach ( i in Get-ChildItem ) {Write-Host i . Name}# with associative reachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits user @ {" frodeh " " Frode Haug " ;" monicas " " Monica Strand " ;" ivarm " " Ivar Moe "}foreach ( key in user . Keys ) {Write-Host user [ key ]}

PowerShellEigil Obrestadand achIf we want to read from the pipeline and do stuff object byobject:# foreach-pipe . ps1Command-line argsInputInputSystem commandsConditionsif/elseOperatorsforeach ( i in input ) { foo @ ( i )}Write-Host " size of foo is " foo . CountSwitch/caseWhereIterationForWhileor# f o r ea c h -o b ject-pipe . ps1ForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits input ForEach-Object { foo @ ( )}Write-Host " size of foo is " foo . Count Get-ChildItem ./ foreach-object-pipe . ps1size of foo is 20

PowerShellOperatorsEigil Obrestadand ator Command-line argsInputInputSystem ereIterationForWhileForeach# math . ps1MathFunctionsRegExpPowerShell examplePowerShellonlyCreditsWrite-Host " 3 5 is " (3 5)MeaningAddSubtractMultiplyDivideModulus

PowerShellFunctionsEigil Obrestadand and-line argsInput# func . ps1InputSystem ell examplePowerShellonlyCredits# declare :function add ( a , b ) {Write-Host " a b is " ( a b )}# use :add 5.12 2.56

PowerShellEigil Obrestadand ErikHjelmåsVariablesArraysRegular expressions intro nd-line argsInputInputSystem commandsConditionsif/else\ ( ) [ ] { } ˆ * ? .These have to be protected with \, l examplePowerShellonlyCreditsTo match c:\temp, you need to use the regexc:\\temp. As a string in C source code, thisregex becomes "c:\\\\temp". Four backslashesto match a single one indeed.(from l):

PowerShellEigil Obrestadand ErikHjelmåsRegular expressions intro 2/5VariablesArraysStructures/ClassesCommand-line argsInputDescribing characters:InputSystem ell ][a-zA-Z0-9]MeaningAny single characterOne of these charactersAny one but these charactersA character in these ranges

PowerShellRegular expressions intro 3/5Eigil Obrestadand ping:Command-line argsInputOperator() InputSystem thFunctionsRegExpPowerShell examplePowerShellonlyCreditsOperatorˆ MeaningBeginning of lineEnd of line

PowerShellEigil Obrestadand ErikHjelmåsRegular expressions intro 4/5VariablesArraysStructures/ClassesCommand-line argsRepetition operators/Modifiers/Quantifiers:InputInputSystem ell examplePowerShellonlyCreditsOperator?* {N}{N,}{N,M}Meaning0 or 1 time0 or more times1 or more timesN timesAt least N timesAt least N but not more than M

PowerShellEigil Obrestadand ErikHjelmåsRegular expressions intro 5/5VariablesArraysStructures/ClassesCommand-line argsInputInputSystem ell examplePowerShellonlyCreditsFinding URLs in HTML:(mailto http)://[ˆ"]*Each line should be an email address:ˆ[A-Za-z0-9. -] @[A-Za-z0-9.-]

PowerShellPowerShell exampleEigil Obrestadand and-line args# regexp . ps1InputInputSystem ell examplePowerShellonlyCredits input ForEach-Object {if ( - match" ˆ[ A-Za-z0-9 . - ] @ ([ A-Za-z0-9 .-] ) " ) {Write-Host " Valid email " , matches [0]Write-Host " Domain is " , matches [1]} else {Write-Host " Invalid email address ! "}}

PowerShellEigil Obrestadand ErikHjelmåsAdvanced stuffVariablesArraysStructures/ClassesCommand-line argsInputInputSystem commandsConditionsif/elseOperatorsSwitch/caseSee the complete Mastering PowerShell book ionForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsfor much more of what you can do with PowerShell

PowerShellEigil Obrestadand sesCommand-line argsInputInputSystem ell index.php/Windows PowerShell 1.0 StringQuoting and Escape kipedia.org/wiki/Windows http://www.regular-expressions.info/OUSTERHOUT, J., “Scripting: Higher-Level Programming for the 21st Century”,IEEE Computer, Vol. 31, No. 3, March 1998, pp. 23-30.)

PowerShell example PowerShell only Credits Hello World # hello.ps1 Write-Host"hello world!" execute as long as filename ends with .ps1:.\hello.ps1 or direct from command line cmd (DOSPROMPT) powershell -command "Write-Host \"hello world!\"" or direct from command line powershell Write-Host"hello world!"