Windows PowerShell Codename: “Monad”. What PowerShell is… Command Line Interpreter Scripting...

Post on 19-Dec-2015

229 views 1 download

Transcript of Windows PowerShell Codename: “Monad”. What PowerShell is… Command Line Interpreter Scripting...

Windows PowerShell

Codename: “Monad”

What PowerShell is…

• Command Line Interpreter• Scripting Language

Things to know about PowerShell

• PowerShell is built directly on top of .NET• PowerShell integrates with WMI (Windows

Management Instrumentation)• PowerShell integrates with COM (Component

Object Model)• This means that PowerShell provides a

powerful and flexible way to administer Windows.

PowerShell versus CMD?

• All usual functionality of CMD is implemented in PowerShell.

• PowerShell can – for ordinary use – be used as though it were CMD.

• As far as scripting goes, forget what you’ve learned about CMD.

• CMD harkens to the DOS/9.x days. PowerShell is .NET.

Using PowerShell

PowerShell is available for:

• Windows Server 2003 (Windows Update)• Windows XP SP3 (Windows Update)• Windows Server 2003 R2 (Windows Update)• Windows Vista (Add/Remove Windows Components)• Windows Server 2008 (Add/Remove Windows Components)• Windows 7 (installed by default)• Windows Server 2008 R2 (installed by default)

Using PowerShell

PowerShell consists of two components: PowerShell CLI (powershell.exe) and PowerShell ISE (powershell_ise.exe). The CLI is a standard terminal. The ISE is a powerful, dedicated, script-producing environment, complete with syntax highlighting.

PowerShell CLI and ISE can be found under:

Start > All Programs > Accessories > Windows PowerShell

PowerShell CLI

PowerShell CLI

If it’s just an ordinary Windows command – “ping” for example – PowerShell will support it and handle it identically to CMD.

You can switch to CMD from PowerShell by typing “cmd” and hitting ENTER. You can switch back by typing “exit” and hitting enter.

By default in PowerShell, “Mark” is turned on, which allows you to highlight and then copy by hitting ENTER.

PowerShell CLI

Different from CMD (but identical to BASH), PowerShell does not include the current working directory in the path, therefore if you want to execute something from the current directory, you must state so explicitly using “./” or “.\” (PowerShell does not differentiate between “/” and “\” for directories).

PowerShell CLI

PowerShell is mostly case-insensitive.

There are ways to make conditional operators either case-sensitive or case-insensitive, covered later…

If you find your terminal getting messy, type “clear” and hit ENTER.

PowerShell CLI

To access editing controls (cut, copy, paste, mark) click the PowerShell icon in the upper-right of the screen:

PowerShell ISE

PowerShell ISE

• Upper section is editor. Create and edit scripts here.

• Middle section is output of executed scripts/commands.

• Bottom section is PowerShell.• Bottom section PowerShell allows line breaks

to execute large script blocks – SHIFT+ENTER. CLI PowerShell does not allow this.

PowerShell ISE

PowerShell scripts save with the extension “ps1”.

By default PowerShell scripts must be “signed” to execute. You will want to disable this:

Open PowerShell “As Administrator”, type:

Set-ExecutionPolicy Unrestricted

Then confirm. Close this prompt afterwards for security reasons.

Getting Help

To get help with a cmdlet, simply invoke “Get-Help” upon it, like so:

Get-Help Get-ChildItem

Aliases for “Get-Help” are “man” and “help”.

PowerShell features tab completion.

PowerShell cmdlets

PowerShell-specific functions are “cmdlets”. They are named according to a VERB-NOUN convention. For example, the functionality of “dir” from CMD is implemented as “Get-ChildItem”.

PowerShell cmdlets are heavily “aliased”. This is a form of substitution that allows you to identify commands by more convenient means.

“Get-ChildItem” has aliases “ls” and “dir”.

PowerShell Pipelines

Pipelining in PowerShell allows you to direct the output of one cmdlet to another.

Pipelining is accomplished by putting a pipe “|” between two cmdlets.

The end of a pipeline is directed to “Write-Output” (which writes text to the terminal) unless directed elsewhere, such as when contained in an evaluation or assigned to a variable.

PowerShell Pipelines

“Get-Member” is a useful cmdlet that allows us to view the “members” of an item. Rather than capturing an item in a variable, and then running it through Get-Member, we can pipe the function that generates that item directly into Get-Member, like this:

Get-ChildItem | Get-Member

This will tell us a lot about the output of Get-ChildItem, such as the various methods that type of output has, as well as the type of output.

PowerShell PipelinesPowerShell pipelines seem like UNIX pipelines, but they are not.

UNIX pipelines typically pipe raw text, PowerShell pipelines pipe objects.

This makes PowerShell pipelines much more powerful.

If you pipe multiple objects, the cmdlet you’re piping to executes for each object being piped.

Get-ChildItem | Write-Output

Will write all objects in the working directory.

PowerShell Variables

A variable in PowerShell is always referenced preceded by a “$”. Variables do not have to be declared before being used, they are created dynamically. Assigning variables is simple:

$i=4

The variable i is now 4.

The Set-Variable cmdlet can be used.

PowerShell Variables

The type of a variable in PowerShell – when it is first created – is chosen for you and may change throughout the variable’s life.

If this is not what you want, you may state this explicitly:

[int32]$i=4

i is now an integer, and is equal to 4.

PowerShell Variables

Enclose variable names in {} to remove ambiguity. Let’s say I have a variable $i and a variable $i2, and I want to print the contents of $i followed immediately by the number 2. I would write:

echo “$i2”

But this would print the contents of $i2, therefore:

echo “${i}2”

PowerShell Variables

PowerShell variables are NOT simply places for storing information. PowerShell variables are powerful objects.

For example, if you invoke Get-ChildItem and store its output in $list, you would expect that you would have a lengthy string.

YOU DO NOT.

What you have is an indexed object of type System.IO.FileInfo.

PowerShell Variables

What this means, is that you can pick an individual file. For example, to print information about the first file, type:

echo $i[0]

“echo” is an alias for “Write-Output”.

Additionally, each file listing in this indexed object IS AN OBJECT ITSELF.

PowerShell Variables

If we want the name of the first file, we can use:

echo $i[0].name

To see a list of all the methods and properties, use:

$i | Get-Member$i[0] | Get-Member

Yes, variables can be piped, because they are objects, and that’s what the pipeline carries.

PowerShell Variables

You can do arithmetic natively when assigning variables:

$i=5+2

$i is now 7. Unlike CMD and BASH, PowerShell supports floating point numbers (type is called “double”).

PowerShell Variables

You can encapsulate cmdlets, commands, and arithmetic inside $() to deal only with their result. If you type “echo 7+2” the print out is “7+2”, however if you type “echo $(7+2)” the output is “9”.

Another example: “echo ipconfig” prints out “ipconfig”, however “echo $(ipconfig)” prints out the result of the command “ipconfig”.

Objects, not simple datastores: “ls[0].name” is bad syntax. “$(ls)[0].name” is fine, and will generate the name of the first file in the directory listing.

PowerShell Variables

Arrays store many objects in an ordered list. Create an array using @() to contain the elements:

$array=@(1,2,3)

This creates an array called $array with three integer elements. You can obtain the length with $array.length, and access the elements by $array[<index>], where the index is between 0 and $array.length-1, inclusive.

Negative numbers index the array in reverse. For the above array, $array[-2] translates into 2, while $array[-1] translates into 3.

PowerShell Variables

PowerShell supports multi-dimensional arrays, that is, arrays with arrays as their elements:

$array=@(@(1,2,3),@(4,5,6),@(7,8,9))

Creates a multi-dimensional array, the first array is an array of three arrays. Then the three sub-arrays have integers as their elements.

A good way to visualize this is as a table or spreadsheet.

You access elements of this array as $array[0][1], etc..

Boolean

In PowerShell the Boolean Type is handled in a C-like way.

[boolean]$truth=326

Will not produce an error, however, if you later try and retrive the object as an integer:

echo $([int32]$truth)

The result will simply be “1”.

Boolean

In PowerShell, much like (but not identical to) C, 0 is False, and non-zero is True.

PowerShell makes this convenient for you by including the built-in, read-only variables $True and $False.

In true C form, you can use 0 and 1 to stand-in for $True and $False. while($True) {} will loop forever, and so will while(1) {}.

while($True) {} is, however, more readable.

PowerShell Methods and Properties

Methods and properties (listings for each type obtained from Get-Member) are accessed by separating them from their object with a period.

These can be nested, and are evaluated left-to-right.

$(ls)[0].name.toCharArray().length

Is valid.

PowerShell Methods and Properties

Since methods actually execute code defined within the object’s class, methods are always followed by at least an opening and closing bracket (possibly containing parameters).

Properties are not followed by brackets.

Examples:

$(ls)[0].name$(ls)[0].delete()

PowerShell Parameters

There are two ways to pass parameters from the CLI to a script in PowerShell, one involves declaring them into individual variables, the other accesses them from an array à la C.

To declare them into variables:

Param($1,$2,…)

The array all parameters are in is called $args. You can therefore ascertain how many parameters were passed with $args.length (very C-like…).

PowerShell Script Formatting

You can use whitespace, semi-colons, or a mixture of both to separate commands in PowerShell:

$i=0;echo $i

Is the same as:

$i=0echo $i

PowerShell Script Formatting

In PowerShell, single-line comments are prefixed with “#”:

# This whole line is a comment!

Multi-line comments are enclosed by <# #>:

<# This isa multi-linecomment! #>

PowerShell Conditions

PowerShell conditional operators are much like BASH’s, and are placed between two values to be compared. The result is either “True” or “False”:

-eq equals-lt less than-le less than or equal to-gt greater than-ge greater than or equal to

PowerShell Conditions

PowerShell conditions – in string or character comparisons – can be switched between case-sensitive or case-insensitive. They are by default case-insensitive. Prepending them with “c” makes the case-sensitive.

(“hi” -eq “HI”)

Is “True”, whereas:

(“hi” -ceq “HI”)

Is “False”.

PowerShell Conditions

PowerShell conditions can be forced to case-insensitivity by prepending “i” as in “-ieq”.

PowerShell Conditions

PowerShell also supports OR, AND, and NOT:

-not Not! Not-or Or-and And

Controlling Script Flow

Curly braces are used to contain “script blocks” in flow control constructs.

PowerShell uses the following flow control constructs:

If…elseif…else…, for…, do…while…, do…until…, while…, try…catch…finally…, trap…, and switch…default…

trap… is largely replaced by try…catch…finally…, the latter being new to PowerShell v2.0.

Controlling Script Flow

IF…ELSEIF…ELSE…

if (condition) {<script block>

} elseif (condition) {<script block>

} else {<script block>

}

“elseif” and “else” are both optional.

Controlling Script Flow

FOR…

for (statement; condition; increment) {<script block>

}

Controlling Script Flow

DO…WHILE…

do {<script block>

} while (condition)

Controlling Script Flow

DO…UNTIL…

do {<script block>

} until (condition)

Controlling Script Flow

WHILE…

while (condition) {<script block>

}

Controlling Script FlowTRY…CATCH…FINALLY…

try {<script block>

} catch [<exception>] {<script block>

} finally {<script block>

}

Either “catch” or “finally” is optional – but not both at the same time. The “[<exception>]” after catch is optional, and in its absence all exceptions will be caught.

Controlling Script Flow

TRAP…

trap [<exception>] {<script block>

}

“[<exception>]” is optional, if omitted all exceptions will be caught.

Controlling Script Flow

SWITCH…DEFAULT…

switch ($variable) {value1 { <script block> }value2 { <script block> }…default { <script block>}

}

“default” is optional.

Controlling Script Flow

Whitespace in control structures is irrelevant, and done only for human readability. The following code writes the numbers 1-100 in the terminal:

$i=1;while ($i -le 100) { echo $i;$i++ }

PowerShell supports:

$var++, $var--, --$var, ++$var

To increment/decrement.

Controlling Script Flow

PowerShell also supports FOREACH, however this construct is special as you can conveniently pipe to it:

@(1,2,3) | foreach { echo $_ }

Or:

foreach ( $i in @(1,2,3) ) { echo $i }

These two are identical in function.

Controlling Script Flow

From anywhere inside a loop, you may skip over the remainder of the loop and cause it to begin with the next iteration immediately with “continue”.

You may end a loop pre-emptively with “break” (“break” can also end other things pre-emptively – including the entire script).

$_

Whenever you have a structure that involves some object, that object is represented within that structure by $_.

The exception that is caught by try…catch…finally…is accessible from the catch block with $_.

In a foreach that you’ve piped to, the element that you’re iterating for is accessible with $_.

Choice and $lastexitcode

“choice” is not a cmdlet, it is an external program.

When external programs are called by PowerShell, they can be used in two ways:

1. The text they produce.2. The code they leave behind upon completion.

The text that a program produces is accessible through $(<external program>).

Choice and $lastexitcode

The code that it leaves behind is accessible through $lastexitcode.

choice records the numerical choice in its exit code. Therefore we test for the choice with a switch statement.

Example on next slide…

Choice and $lastexitcode

choice /n /c ABCD /m “Please enter one of the first four letters` of the alphabet: “switch ($lastexitcode) {1 { echo “You entered A!” }2 { echo “You entered B!” }3 { echo “You entered C!” }4 { echo “You entered D!” }}

Grave

The grave (“`”, shares a key with tilde (“~”)) is the escape character in PowerShell. It is used to break between lines in code without causing the interpreter to believe you’re starting a new command.

It is also used to denote special characters in strings (see next slide).

Graves, single and double quotes, and dollar signs that you wish to appear in strings must be escaped:

echo “``”

Prints “`” to the terminal.

Grave

Special Characters:

`0 = Null`a = Alert`b = Backspace`n = New line`r = Carriage return`t = Horizontal tab`’ = Single quote`” = Double Quote`` = Grave`$ = Dollar sign

InterpolationIn many programming languages, the single and double quote are interchangeable, not so in PowerShell.

Double quotes around a string cause variables in that string to be substituted for themselves, single quotes around a string disable this behaviour:

$i=“Robert”;echo “I am $i”

Prints “I am Robert”.

$i=“Robert”;echo ‘I am $i’

Prints “I am $i”.

Functions

PowerShell allows you to define functions, both in a script and in separate modules.

Functions are identified by:

function <name> (<args>) { <script block> }

If the function does not accept arguments, you do not need to include the parenthesis.

Functions use the “return” statement to pass objects back to where they were called from.

Functions

Functions are invoked simply by typing their name as you would with a cmdlet. If you wish to pass them arguments you separate the arguments from the function call and one another with a space.

function concatenatestrings ($x,$y) { return “$x$y” }echo $(concatenatestrings “h” “i”)

Prints “hi”.

Functions

You can treat almost anything that contains a script block in PowerShell as a function – and therefore have it return a value.

[boolean]$trueorfalse=$True$i=$( if ($trueorfalse) { return 1 } else { return 0 } )echo $i

Will print “1”.

Also: Return does not necessarily have to return anything. It can simply be used to exit the context of a function.

Modules

PowerShell Modules are saved as .psm1 files.

PowerShell Modules contain functions.

PowerShell Modules are imported using the cmdlet Import-Module.

Once imported you may call the functions of a module as if they were defined within the current script.

Modules

If you want to make certain functions in a module private, you can do so by ending the module file with the cmdlet “Export-ModuleMember” followed by a quantification of the functions you want to be public. You can use a comma-delimited list, wildcard characters, etc.. The following makes all functions public:

Export-ModuleMember *

And should be included as good form if you want all functions to be public.