Intro to Power Shell Scripting Author Prof Leon

  • Slides: 26
Download presentation
Intro to Power. Shell Scripting Author: Prof Leon King Last Updated: Dec 19, 2019

Intro to Power. Shell Scripting Author: Prof Leon King Last Updated: Dec 19, 2019 Time spent: est 6 -7 hrs

Power. Shell is an interpreted scripting language that allows one to modify and control

Power. Shell is an interpreted scripting language that allows one to modify and control the Windows environment It is similar in concept to various Unix shells such as csh and bash, but the commands and flags are more verbose. And whereas Unix shell commands are viewed as a stream of text, the output of Power. Shell commands are objects where fields can be treated as member variables. Like bash is to Unix, Powershell should be seen as a full programming language, specialized to handle Windows files and processes.

Central to Power. Shell is the idea of pipelines cmd 1 -flag 1 arg

Central to Power. Shell is the idea of pipelines cmd 1 -flag 1 arg -flag 2 arglist | cmd 2 …. | cmd 3 Like Unix pipelines, the output of one command can be streamed as the input to the next. The initial command is known as a provider as it provides fresh data. The following commands are called filters as they should always modify the data from the previous command. Whereas bash predefines 2 default output streams, stdout and stderr, Power. Shell predefines 7: 1 regular output/success 2 error 3 warning 4 verbose 5 debug 6 information progress (not used in redirection)

Common Programming Language Features • • • Comments Data Types Variable Declarations Operators and

Common Programming Language Features • • • Comments Data Types Variable Declarations Operators and Expressions Flow of Control Statements Functions and Subroutines Macros and Preprocessor Commands I/O Statements Libraries External Tools (Compiler, debugger etc)

Comments #This is a single line comment, just like bash. <# This is a

Comments #This is a single line comment, just like bash. <# This is a block comment that can span multiple lines #>

Built in Data Types and Constants “This is a String” ‘And so is this’

Built in Data Types and Constants “This is a String” ‘And so is this’ @’ This is a here string. It can contain evaluated expressions ${2*50 +7}. And it’s for apostrophes and quote sysmbols. You can also use @” and “@ It ends with ‘@ in column 1 and 2 ‘@ $True, $False #booleans 42, 0 x. CA 12 F 7 #decimal, and hex are all [int] #used to be 32 bit, now 64 bit 22. 7, 22 e-5 #floating point numbers [double] 1. . 10; 5. . -2 #generate ranges of numbers. The type is [array] [datetime] “ 18 Sept 2020 8: 40: 22 AM” #dates – time can be left out Other types: include [timespan], [guid], [array], [hashtable] , [psobject] and [scriptblock]

Variable Declarations • • All variables begin with a $ sign followed by at

Variable Declarations • • All variables begin with a $ sign followed by at least one letter. Variables do not have to be declared. They are created on 1 st use. Variables and keywords are case insensitive in Power. Shell is a weakly typed language – a variable can switch between different data types, depending on how it is used. $x=21 $x=“Hello World” The new-variable command can be used to declare a variable global or private (local) to a block of code.

Variable Declarations: Array Notation $my. Array=@(5; 12. 2*17, ”Hello World”, 7. . 15) $my.

Variable Declarations: Array Notation $my. [email protected](5; 12. 2*17, ”Hello World”, 7. . 15) $my. Array= 1, 2, ”hello”, 17. 2, 0 x 1 b $my. Array[0] is 5. $my. Array[4] is 8. Since Power. Shell is loosely typed the elements of the array can be mixed data types.

Variable Declarations: Hash Tables Arrays use (). Hash Tables use { } $my. Hash.

Variable Declarations: Hash Tables Arrays use (). Hash Tables use { } $my. Hash. [email protected]{name=“Joe”; age=23; profession=‘Programmer’} $my. Hash. Table[‘name’] is “Joe”

Operators

Operators

Assignment = works as you’d expect it to: $a=7; $b=($a+($c=11)); //assignment as a side

Assignment = works as you’d expect it to: $a=7; $b=($a+($c=11)); //assignment as a side effect in expr This is interesting: $a, $b, $c = “Hello”, 17, 21

Arithmetic Operators Standard C arithmetic operators will work ++ -* / % + +=

Arithmetic Operators Standard C arithmetic operators will work ++ -* / % + += -= *= /= %= ? : (triadic operator) #New to version 7, old to C and Java The + operator also concatenates Strings: 5+5 becomes 10, ‘ 5’+’ 5’ becomes ‘ 55’ - this could create problems result=‘Hello ’+’world!

Relational Operators Similar to the bash shell, but used for all comparissons $x $x

Relational Operators Similar to the bash shell, but used for all comparissons $x $x -le $y -ge $y -lt $y -gt $y -eq $y -ne $y -xor $y Add the letter c to make string comparissons case sensitive $x -clt $y

Logical Operators Compare two logical values or expressions: $x -or $y $x -xor $y

Logical Operators Compare two logical values or expressions: $x -or $y $x -xor $y $x -and $y $x -eqv $y #At least one of $x or $y is true #only one of $x or $y is true #both of $x and $y is true #$x and $y are the same

Additional Operators To do: string, bitwise operators, regular expressions See: http: //docs. Microsoft. com/enus/powershell/module/powershell.

Additional Operators To do: string, bitwise operators, regular expressions See: http: //docs. Microsoft. com/enus/powershell/module/powershell. core/about_operators? view =powershell-7

Math Functions [math]: : pow($x, $y) Math functions are made available from the. NET

Math Functions [math]: : pow($x, $y) Math functions are made available from the. NET library. The notations reads: Use function pow contained in the class [math]. Some other useful functions are…. .

The Cast Operator [type] value $x = [int] 12. 2 To Do: add some

The Cast Operator [type] value $x = [int] 12. 2 To Do: add some more examples

Flow of Control: if, then, elseif if(condition) {list of statements…} elseif(condition) {list of statements…}

Flow of Control: if, then, elseif if(condition) {list of statements…} elseif(condition) {list of statements…} else {list of statements…} The format of an if statement is fairly easy to master. It’s similar to a version of if in the bash shell.

Flow of Control: switch statement $result= switch($value) { 1 {“One”; break; } 2 {“Two”}

Flow of Control: switch statement $result= switch($value) { 1 {“One”; break; } 2 {“Two”} “Hello” {“Three”} 4 {do something…; "Four"} } The value of the last expression in each block is the result of the switch. The addition of break is optional. If not used the switch statement might match another case This needs a bit more work. Switch will take a pipeline as an argument, also multiple values, ie: switch(4, 2) …. , matching all items

Flow of control: counting for loop for($i=1; $i -le 10; $i++) { #Insert statements

Flow of control: counting for loop for($i=1; $i -le 10; $i++) { #Insert statements }

Flow of Control: while loop while($true) { list of statements…. }

Flow of Control: while loop while($true) { list of statements…. }

Flow of Control: for each loop foreach($item in $my. Array) echo $item foreach($file in

Flow of Control: for each loop foreach($item in $my. Array) echo $item foreach($file in get-child. Item) #lists files in a directorty write-host $file

Defining a function Function my. Function { write-host “Executing my. Function” return 2 }

Defining a function Function my. Function { write-host “Executing my. Function” return 2 } my. Function Output: Executing my. Function 2 $x=my. Function # $x becomes both the result of write-host and return.

Defining a function with parameters function 2 { param( [string] $username, [int] $score) write-output

Defining a function with parameters function 2 { param( [string] $username, [int] $score) write-output “Hello $username “ write-output “Your score is: “, $score } Function 2 “Bob Smith” 72 Output: Hello Bob Smith Your score: is 72 The use of [type] is optional and expresses an expected data type

Defining a function with default param values Using named parameters function 4 { param(

Defining a function with default param values Using named parameters function 4 { param( [string] $username=“Tina Sims”, [int] $score=75) write-output “Hello $username. Your score is: “, $score } function 4 “Dana Andrews” Output: Hello Dana Andrews Your score: is 75 function 4 -score 42 Output: Hello Tina Sims Your score is 42

To Do • • More on builtin functions Input String manipulation (read-host doesn’t parse

To Do • • More on builtin functions Input String manipulation (read-host doesn’t parse anything) Formating strings using -f option • Redirection of the 5 output streams. Look into sub processes here. Should be able to find/verify use of tee with a stream, ie: provider | tee $( 1> filter. A | filter…) $(2> filter. Z | filter Y…. ) $(3> filter. Alpha | filter. Beta) $(4> filter. Gamma…) $(5> filter. Zeta | …. ) • Or: provider 1>$output. Result 2>$error. Result 3>$info. Result 4>$verbose. Result 5>$debug. Result • 1 st do a simple example using strings • 2 nd do an example where each stream produces object