0% found this document useful (0 votes)
2 views23 pages

Module 3 (1)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 23

 Windows PowerShell provides a command-line interface as well as a powerful scripting language.

 As with any scripting language, PowerShell provides a number of languages constructs that let you
control the flow of your script as well as make decisions about what it should do. These language
constructs are the if, switch, for, break, continue, foreach, while, and do statements.

Importing Contents
a. TEXT Files

Once you have a file, you can use PowerShell to import the contents. For this example, will import
the contents of Cities.txt.

The contents have been successfully imported. We can see what type of object we're working with by
piping $Cities to Get-Member.

Looks like we are working with an array of strings. We can see this by using the Count property, as
well as taking a look at the first value in the array, which would be reflected as $Cities[0].

b. CSV Files

Importing the Users.csv file


Counting the number of users in the file

Accessing each object

Arrays
a. Comma-separated array

When you use , to separate values, PowerShell automatically interprets them as an array. This is a shorthand
way to create an array, and it’s convenient for simple array assignments.

Syntax: $myarr1 = 1, 2, 3

Automatically creates an array with the values 1, 2, and 3.

b. Array subexpression operator-


The @( ) syntax is an explicit array subexpression. This means you’re intentionally specifying that what’s
inside the parentheses should be treated as an array, even if it only contains one or zero items. Forces
PowerShell to treat the enclosed items as an array.

PowerShell, arrays can contain elements of different types. PowerShell arrays are heterogeneous, meaning they
can hold a mix of data types, such as integers, strings, booleans, objects, etc.

For example:

$myarr1 = 1, 2, "apple", $true, 3.14


Here,

 1 and 2 are integers.


 "apple" is a string.
 $true is a boolean.
 3.14 is a floating-point number.

Checking Element Types

You can check the type of each element

foreach ($element in $myarr1) {


$element.GetType().Name
}
c. Sorting an array

d. Removing elements from the array


e. Delete an array

f. Looping through arrays


g. MULTI-DIMENSIONAL ARRAY - size of each row is same

h. JAGGERED ARRAY – a type of multi-dimensional array where size of all rows may be
different.
Jagged and multidimensional arrays are useful for holding lists of lists and arrays of arrays.
• Jagged arrays are arrays of arrays, where each array has only as many elements as it needs.
• A nonjagged array is more like a grid or matrix, where every array needs to be the same size.
• Jagged arrays are much easier to work with (and use less memory), but nonjagged multidimensional
arrays are sometimes useful for dealing with large grids of data.
• Since a jagged array is an array of arrays, creating an item in a jagged array follows the same rules as
creating an item in a regular array.
• If any of the arrays are single-element arrays, use the unary comma operator

i. To create an array of a specific size, use the New-Object cmdlet: explain with example
j. Combining two arrays

Conditions

Decision making structures have one or more conditions to be evaluated or tested by the programme,
along with a statement or statements that are to be executed if the condition is determined to be true,
and optionally, other statements to be executed if the condition is determined to be false.

Following is the general form of a typical decision-making structure found in most of the
programming languages

PowerShell scripting language provides following types of decision-making statements.

A. if statement –
An if statement consists of a Boolean expression followed by one or more statements.

B. if-else statement-
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false
C. nested if statement-
You can use one if or else if statement inside another if or else if statement(s).

D. if-else ladder
//Find the smallest of 3 numbers
if ($x -lt $y) {
if ($x -lt $z) {
Write-Host $x "is the smallest"
} else {
Write-Host $z "is the smallest"
}
} elseif ($y -lt $z) {
Write-Host $y "is the smallest"
} else {
Write-Host $z "is the smallest"
}
E. switch statement-
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each case.
Syntax The syntax of enhanced for loop is;

The following rules apply to a switch statement;


• The variable used in a switch statement can only be an object or an array of objects.
• You can have any number of case statements within a switch. Each case is followed by
optional action to be performed.
• The value for a case must be the same data type as the variable in the switch, and it must be
a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
CREATING A RANDOM PASSWORD USING
POWERSHELL

•Passwords have always been a popular topic for discussion in IT security.

• PowerShell lends itself well to the generation of individual random passwords.

•Powershell allows you to create secure passwords automatically with a customised script.

• In this topic, you will learn to write a script that helps you to create passwords which comply with
your security policies.

• Moreover, it will allow for simple adjustments if the policies are changing.
1. Get-Random cmdlet specifies the set of items from which random values will be chosen.

2. [byte][char]’character’

3. Find byte values for upper case character set

4. Create separate character sets

3.

PS C:\Windows\system32> $upperCaseSet=(65..90) | foreach{[char]$_}


PS C:\Windows\system32> $lowerCaseSet=(97..122) | foreach{[char]$_}

PS C:\Windows\system32> $numericSet=(48..57) | foreach{[char]$_}

PS C:\Windows\system32> $specialSet=(33,35,36,37,38,42,63) | foreach{[char]$_}

PS C:\Windows\system32> $charSet= $upperCaseSet+$lowerCaseSet+$numericSet+$specialSet

PS C:\Windows\system32> -join(Get-Random -Count 10 -InputObject $charSet)

ACCEPTING USER INPUT


Using the Read-Host PowerShell cmdlet, you can interactively prompt for input from the script user. •
Let us see some real-world applications on how we can use the Read-Host PowerShell cmdlet.

• Prompting for Input with Read-Host

• The Read-Host cmdlet performs two functions in a PowerShell script.

• It pauses execution and receives input.

• That's it. Read-Host is a simple cmdlet but one that comes in useful when needing to get information
from the script user.

This Prompt parameter allows you to give the script user some kind of indication as to what to input.
For example, if your script requires a server name, you might choose to use Read-Host to prompt the
user to input that when the script is run.
Asking for Passwords
Let us say you have a deep, dark secret you do not want anyone to know about, but you need to pass
this password to some kind of software. When you do not use AsSecureString, you are onto me!
However, if you use AsSecureString, my secret is safe since every character you type is replaced with
an asterisk and the output is saved as a secure string rather than a plain-text string.

HASH TABLES
Hash Tables are unordered data types unlike arrays which are ordered and indexed.
 To get the type of hash table

 To display all keys

 To display all values

 There are two ways to access specific values of the keys


a.
 To check if a key exist or not

 To check if a value exist

 To add values to a hash table


 To update values on a hash table
 To remove objects/values from a hash table

 An example we can use a hash table for could be if we have a bunch of employees, with
employee ids as the keys and their names as the respective values.
 Another example for hash table could be of an inventory system where the keys could be the
product number or barcode numbers or names and values could be the price of the item.

CREATING CUSTOM OBJECTS


 Create a custom object using New-Object cmdlet

 Adding properties to the object created using Add-Member cmdlet


 To check the object members

 Casting Hash Table into a custom object


ERROR HANDLING
The first requirement is to understand the types of errors that can occur during execution.
Terminating vs. Non-Terminating Errors:

• Terminating Error: A serious error during execution that halts the command (or script execution)
completely. Examples can include non-existent cmdlets, syntax errors that would prevent a cmdlet
from running, or other fatal errors.

• Non-Terminating Error: A non-serious error that allows execution to continue despite the failure.
Examples include operational errors such file not found, permissions problems, etc.

Try/Catch Blocks:

• The Try and Catch statements allow us to control script flow when we encounter errors.
• The statements behave similarly to the statements of the same name found in C# and other
languages.

• The behaviour of try/catch is to catch terminating errors (exceptions).

• This means Non-terminating (operational) errors inside a try block will not trigger a Catch*.

• If you would like to catch all possible errors (terminating and non-terminating) – then simply set
the error action preference to Stop.

• Remember that Stop error action forces a non-terminating error to behave like a terminating error.

The error here is not caught as the error is non-terminating.

We may check the following-

Error Action Preference: Available choices for error action preference:

a. Silently Continue – error messages are suppressed and execution continues.


b. Stop – forces execution to stop, behaving like a terminating error.
c. Continue – the default option. Errors will display, and execution will continue.
d. Inquire – prompt the user for input to see if we should proceed.
e. Ignore – (new in v3) – the error is ignored and not logged to the error stream. Has very
restricted usage scenarios.
OR

The $error variable


• When either type of error occurs during execution, it is logged to a global variable called $error.

• This variable is a collection of PowerShell Error Objects with the most recent error at index 0.

• On a freshly initialised PowerShell instance (no errors have occurred yet) the $error variable is
ready and waiting as an empty collection:

You might also like