Input PowerShell Tutorial - ELTE

Transcription

PowerShellTutorialErik ine argsInputInputPowerShell TutorialSystem commandsConditionsif/elseOperatorsSwitch/caseErik RegExpPowerShell examplePowerShellonlyCreditsMarch 22, 2011

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

PowerShellTutorialErik ommand-line argsInputInputSystem commandsThe following presentation is NOT meant to be acomprehensive/complete tour of the PowerShell eIterationThe purpose is to get you started with some basic programconstructions which you will recognize based achMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsAt the end of the presentation (Credits section) you will findpointers to more comprehensive material (referencematerial).

PowerShellTutorialErik ommand-line argsInputInputSystem commandsConditionsYou need a Windows host running on a physical or virtualmachine with working access to the internet, and withPowerShell v2.0 nForLog in and open a terminal window, download the examplesas we go along fromhttp :// www . hig . no / erikh / tutorial-powershell / FILENAMEWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits(or download all at once with filenamepowershell-examples.zip but remember to unblock beforeunzip)

PowerShellTutorialHello WorldErik HjelmåsVariablesArraysStructures/Classes# hello . ps1Command-line argsInputInputWrite-Host " hello world ! "System execute as long as filename ends with .ps1:.\ hello . rShell examplePowerShellonlyCreditsor direct from command line cmd (DOSPROMPT)powershell - command " Write-Host \ " hello world !\ " "or direct from command line powershellWrite-Host " hello world ! "

PowerShellTutorialSingle VariablesErik ine argsInputInput# single-var . ps1System IterationForWhile firstname " Mysil " lastname " Bergsprekken " fullname " firstname lastname "Write-Host " Hello fullname , may I call you firstname ? "ForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsAll variables are prefixed with

PowerShellTutorialSingle and Double QuotesErik ine argsInputInputSystem ell examplePowerShellonlyCredits# quotes . ps1 name " Mysil "Write-Host HelloWrite-Host " HelloWrite-Host ' Hello name name " name '

PowerShellTutorialArraysErik ine argsInputInputOne-dimensional arrays:System commandsConditions# array . leForeach os @ ( " linux " , " windows " ) os @ ( " mac " )Write-Host os [1]# print windowsWrite-Host os# print entire arrayWrite-Host os . Count # length of arrayMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsArrays are created with @(.)

PowerShellTutorialAssociative ArraysErik ine argsInput# assoc-array . ps1InputSystem IterationForWhileForeachMath user @ {" frodeh " " Frode Haug " ;" ivarm " " Ivar Moe "} user @ { " lailas " " Laila Skiaker " }Write-Host user [ " ivarm " ] # print Ivar MoeWrite-Host @user# print entire arrayWrite-Host user . Count# print length of arrayFunctionsRegExpPowerShell examplePowerShellonlyCreditsAssociative arrays are created with @{.}

PowerShellTutorialStructures/ClassesErik HjelmåsVariablesArraysA simple object used as a struct:Structures/ClassesCommand-line args# struct . ps1InputInputSystem 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 " ]

PowerShellTutorialErik HjelmåsCommand-Line line argsInputInputSystem commandsConditionsif/elseAll command-line arguments in the array argsScriptname retrieved from the object MyInvocationOperatorsSwitch/case# cli-args . pPowerShell examplePowerShellonlyCreditsWrite-Host " I am " MyInvocation . InvocationName " and have " args . Count " arguments " " first is " args [0]

PowerShellTutorialInput From UserErik ine argsInputInputSystem commandsConditionsif/else# input-user . chMathFunctionsRegExpPowerShell examplePowerShellonlyCredits something Read-Host " Say something here "Write-Host " you said " something

PowerShellTutorialInput From the PipelineErik ine argsInputInputSystem commandsConditionsif/elseOperatorsSwitch/case# input-pipe . ps1 something " input "Write-Host " you said " sRegExpPowerShell examplePowerShellonlyCreditscan be executed asWrite-Output " hey hey ! " .\ input-pipe . ps1

PowerShellTutorialInput From FilesErik ine argsInputInputSystem commandsConditionsif/else# input-file . chMathFunctionsRegExpPowerShell examplePowerShellonlyCredits file Get-Content hello . ps1Write-Host @file - Separator " n "

PowerShellTutorialErik HjelmåsInput from System ine argsInputInputSystem commands# input-commands . tionForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits name ( Get-WmiObject Win3 2 Op erat ingSy stem ). 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 ) "

PowerShellTutorialif/elseErik ine argsInputInputSystem commands# if . tionForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsif ( args . Length - ne 1) {Write-Host " usage : " MyInvocation . InvocationName " argument "}

PowerShellTutorialComparisonErik ine argsInputInputSystem ell q-neMeaningLess thanGreater thanLess than or equal toGreater than or equal toEqual toNot equal to

PowerShellTutorialBooleanErik ine argsInputInputSystem ell aningNotNotAndOr

PowerShellTutorialErik ine 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 "}}

PowerShellTutorialBoolean exampleErik HjelmåsVariablesArraysStructures/Classes# if-bool . ps1Command-line argsInputInputSystem commandsConditionsif/elseOperatorsSwitch/caseif ((1 - eq 2) - and (1 - eq 1) - or (1 - eq 1)) {Write-Host " And has precedence "} else {Write-Host " Or has precedence "}WhereIterationFor# force OR precedence :WhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsif ((1 - eq 2) - and ((1 - eq 1) - or (1 - eq 1))) {Write-Host " And has precedence "} else {Write-Host " Or has precedence "}

PowerShellTutorialSwitch/CaseErik ine argsInput# switch . ps1InputSystem 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 ? " }}

PowerShellTutorialWhere/Where-ObjectErik ine argsInputInputSystem commandsConditionsif/else# where . chMathFunctionsRegExpPowerShell examplePowerShellonlyCreditsGet-ChildItem Where-Object { . Length - gt 1 KB }

PowerShellTutorialFor loopErik HjelmåsVariablesArraysStructures/Classes# for . ps1Command-line argsInputInputSystem commandsConditionsfor ( i 1; i-le3 ; i ) {Write-Host " i "}if/elseOperatorsSwitch/case# something more useful owerShell 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 "}}

PowerShellTutorialWhileErik HjelmåsVariables# while . ps1ArraysStructures/ClassesCommand-line argsInputInputSystem commandswhile ( i - le 3) {Write-Host i i }Conditionsif/elseOperators# something more useful ionsRegExpPowerShell 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 }

PowerShellTutorialForeach loopErik HjelmåsVariablesArraysStructures/Classes# foreach . ps1Command-line argsInputInputSystem commandsConditionsforeach ( i in Get-ChildItem ) {Write-Host i . Name}if/elseOperatorsSwitch/case# with associative gExpPowerShell examplePowerShellonlyCredits user @ {" frodeh " " Frode Haug " ;" monicas " " Monica Strand " ;" ivarm " " Ivar Moe "}foreach ( key in user . Keys ) {Write-Host user [ key ]}

PowerShellTutorialForEachErik HjelmåsVariablesArraysIf we want to read from the pipeline and do stuff object byobject:Structures/ClassesCommand-line args# foreach-pipe . ps1InputInputSystem ch ( i in input ) { foo @ ( i )}Write-Host " size of foo is " foo . ExpPowerShell examplePowerShellonlyCreditsor# f o r ea c h -o b ject-pipe . ps1 input ForEach-Object { foo @ ( )}Write-Host " size of foo is " foo . Count Get-ChildItem ./ foreach-object-pipe . ps1size of foo is 20

PowerShellTutorialOperatorsErik ine argsOperatorInputInput System erShell examplePowerShellonlyCredits# math . ps1Write-Host " 3 5 is " (3 5)MeaningAddSubtractMultiplyDivideModulus

PowerShellTutorialFunctionsErik ine argsInputInputSystem commands# func . tionForWhileForeachMathFunctionsRegExpPowerShell examplePowerShellonlyCredits# declare :function add ( a , b ) {Write-Host " a b is " ( a b )}# use :add 5.12 2.56

PowerShellTutorialErik HjelmåsRegular expressions intro haracters:Command-line argsInput\ ( ) [ ] { } * ? .InputSystem commandsConditionsif/elseThese have to be protected with , e.g.http://www .hig .noOperatorsSwitch/caseWhereIn other languages it is common to use \:IterationForWhileForeachMathFunctionsTo 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.RegExpPowerShell examplePowerShellonlyCredits(from l):

PowerShellTutorialErik HjelmåsRegular expressions intro 2/5VariablesArraysStructures/ClassesCommand-line argsInputInputSystem commandsDescribing rShell examplePowerShellonlyCreditsOperator.[abcd][ abcd][a-zA-Z0-9]MeaningAny single characterOne of these charactersAny one but these charactersA character in these ranges

PowerShellTutorialRegular expressions intro 3/5Erik ine argsGrouping:InputInputOperator() System thFunctionsRegExpPowerShell examplePowerShellonlyCreditsOperator MeaningBeginning of lineEnd of line

PowerShellTutorialErik HjelmåsRegular expressions intro 4/5VariablesArraysStructures/ClassesCommand-line argsInputRepetition operators/Modifiers/Quantifiers:InputSystem 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

PowerShellTutorialErik HjelmåsRegular expressions intro 5/5VariablesArraysStructures/ClassesCommand-line argsInputInputSystem ng URLs in HTML:(mailto http)://[ pPowerShell examplePowerShellonlyCreditsEach line should be an email address: [A-Za-z0-9. -] @[A-Za-z0-9.-]

PowerShellTutorialPowerShell exampleErik ine argsInput# regexp . ps1InputSystem 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 ! "}}

PowerShellTutorialErik HjelmåsAdvanced stuffVariablesArraysStructures/ClassesCommand-line argsInputInputSystem commandsConditionsif/elseSee the complete Mastering PowerShell book hMathFunctionsRegExpPowerShell cs/blogs/ebook/for much more of what you can do with PowerShell

PowerShellTutorialErik mmand-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 Tutorial Erik Hjelmås Variables Arrays Structures/Classes Command-line args Input Input System commands Conditions if/else Operators Switch/case Where Iteration For While Foreach Math Functions RegExp PowerShell example PowerShell only Credits PowerShell Tutorial Erik Hjelmås March 22, 2011. PowerShell Tutorial Erik Hjelmås