You are on page 1of 54

EXPLAIN THE TOP DOWN DESIGN OF SHELL SCRIPT

This process of identifying the top-level steps and developing increasingly


detailed views of those steps is called top-down design. This technique allows us
to break large, complex tasks into many small, simple tasks. Top-down design is
a common method of designing programs and one that is well suited to shell
programming in particular.

A top-down design is the decomposition of a system into smaller parts in order


to comprehend its compositional sub-systems.

In top-down design, a system's overview is designed, specifying, yet not


detailing any first-level subsystems

A top-down design is also known as a stepwise design.

A top-down design is generally a plan made in plain, simple English for the
program. It is very important to note that a top-down design must be
independent of any programming language. The top-down design must never
incorporate references to library functions or syntactic elements specific to a
particular language.

That is the reason why top-down designs are written in plain English. The
concept driving a top-down design is to break up the task that a program
executes into a very few extensive subtasks.

The highest level is known as the main module, top level or level 0. At this point,
the volume of subtasks must be small. Most programs at this level usually
include three to seven subtasks. For small-sized programs, the volume of
subtasks must be at the low end of the mentioned range.

Division of tasks into subtasks essentially splits the problem into various smaller
programs, which helps developers to easily code these simpler parts. It is
usually possible that many of these subtasks are so basic that they can
immediately determine how to write the code to complete that part.

However, this is generally not the case at the top level. If a subtask takes more
than a very few lines of code, it is recommended to repeat the subdivision
process. Typically, for every subtask at top level, a new module is started at
level 1. These subtasks are then considered individually, and yet again divided
into various other subtasks. This subdivision and new level creation processes
should be continued until the coders can implement every portion of the problem
using computer code.

Example
we will use top-down design to further develop our report-generator script.

Shell Functions

Our script currently performs the following steps to generate the HTML
document:
1. Open page.

2. Open page header.

3. Set page title.

4. Close page header.

5. Open page body.

6. Output page heading.

7. Output timestamp.

8. Close page body.

9. Close page.

EXPLAIN LOOP CONTROL CONDITION WITH EXAMPLE SHELL SCRIPT

Looping Statements | Shell Script


Looping Statements in Shell Scripting: There are total 3 looping statements
which can be used in bash programming 
 
1. while statement
2. for statement
3. until statement
To alter the flow of loop statements, two commands are used they are, 
 
1. break
2. continue
Their descriptions and syntax are as follows: 
 
 while statement 
Here command is evaluated and based on the result loop will executed, if
command raise to false then loop will be terminated 
Syntax 
 while [ condition ] do
command1
command2
done

 for statement 
The for loop operate on lists of items. It repeats a set of commands for
every item in a list. 
Here var is the name of a variable and word1 to wordN are sequences of
characters separated by spaces (words). Each time the for loop executes,
the value of the variable var is set to the next word in the list of words,
word1 to wordN. 
Syntax 
 
 for var in list
do
command 1
command 2
done

 until statement 
The until loop is executed as many as times the condition/command
evaluates to false. The loop terminates when the condition/command
becomes true. 
Syntax 
 until [ conditional statement ] do
command1
command2
done
 break
The break statement is used to terminate the loop and can be used
within a while, for, until, and select loops.
Syntax
break [N]
// N is the number of nested loops.
// This parameter is optional.
// By default the value of N is 1.
 continue
Continue is a command which is used to skip the remaining command
inside the loop for the current iteration in for, while, and until loop. 
Syntax:
continue [N]
// the optional parameter N specifies the nth enclosing loop
to continue from.
// This parameter is optional.
// By default the value of N is 1.

 
Example Programs
Example 1: 
Implementing for loop with break statement 
 

 php
#Start of for loop
for a in 1 2 3 4 5 6 7 8 9 10
do
    # if a is equal to 5 break the loop
    if [ $a == 5 ]
    then
        break
    fi
    # Print the value
    echo "Iteration no $a"
done

Output 
 
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Example 2: 
Implementing for loop with continue statement 
 

 php

for a in 1 2 3 4 5 6 7 8 9 10
do
    # if a = 5 then continue the loop and
    # don't move to line 8
    if [ $a == 5 ]
    then
        continue
    fi
    echo "Iteration no $a"
done

Output 
 
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Iteration no 6
Iteration no 7
Iteration no 8
Iteration no 9
Iteration no 10
Example 3: 
Implementing while loop 
 

 php

a=0
# -lt is less than operator
 
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
    # Print the values
    echo $a
     
    # increment the value
    a=`expr $a + 1`
done

Output: 
 
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
Example 4: 
Implementing until loop 
 

 php

a=0
# -gt is greater than operator
 
#Iterate the loop until a is greater than 10
until [ $a -gt 10 ]
do
    # Print the values
    echo $a
     
    # increment the value
    a=`expr $a + 1`
done

Output: 
 
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
10
Example 5: Infinite loop

 PHP

while true
do
  # Command to be executed
  # sleep 1 indicates it sleeps for 1 sec
  echo "Hi, I am infinity loop"
  sleep 1
done

Output:
$bash -f main.sh
Hi, I am infinity loop
Hi, I am infinity loop
Hi, I am infinity loop
.
.
.
.
It continues

EXPLAIN A POWER SHELL SCRIPT COMMEND LET AND ADV COMMEND


LET

A cmdlet is a lightweight command that is used in the PowerShell environment.


The PowerShell runtime invokes these cmdlets within the context of automation
scripts that are provided at the command line. The PowerShell runtime also
invokes them programmatically through PowerShell APIs.

Cmdlets

Cmdlets perform an action and typically return a Microsoft .NET object to the
next command in the pipeline. A cmdlet is a single command that participates in
the pipeline semantics of PowerShell. This includes binary (C#) cmdlets,
advanced script functions, CDXML, and Workflows.

This SDK documentation describes how to create binary cmdlets written in C#.
For information about script-based cmdlets, see:

 about_Functions_Advanced
 about_Functions_CmdletBindingAttribute
 about_Functions_Advanced_Methods

To create a binary cmdlet, you must implement a cmdlet class that derives from
one of two specialized cmdlet base classes. The derived class must:

 Declare an attribute that identifies the derived class as a cmdlet.


 Define public properties that are decorated with attributes that
identify the public properties as cmdlet parameters.
 Override one or more of the input processing methods to process
records.

You can load the assembly that contains the class directly by using the Import-
Module cmdlet, or you can create a host application that loads the assembly by
using the System.Management.Automation.Runspaces.Initialsessionstate API.
Both methods provide programmatic and command-line access to the
functionality of the cmdlet.

Cmdlet Terms

The following terms are used frequently in the PowerShell cmdlet


documentation:
Cmdlet attribute

A .NET attribute that is used to declare a cmdlet class as a cmdlet. Although


PowerShell uses several other attributes that are optional, the Cmdlet attribute
is required. For more information about this attribute, see Cmdlet Attribute
Declaration.

Cmdlet parameter

The public properties that define the parameters that are available to the user or
to the application that is running the cmdlet. Cmdlets can have required, named,
positional, and switch parameters. Switch parameters allow you to define
parameters that are evaluated only if the parameters are specified in the call.
For more information about the different types of parameters, see Cmdlet
Parameters.

Parameter set

A group of parameters that can be used in the same command to perform a


specific action. A cmdlet can have multiple parameter sets, but each parameter
set must have at least one parameter that is unique. Good cmdlet design
strongly suggests that the unique parameter also be a required parameter. For
more information about parameter sets, see Cmdlet Parameter Sets.

Dynamic parameter

A parameter that is added to the cmdlet at runtime. Typically, the dynamic


parameters are added to the cmdlet when another parameter is set to a specific
value. For more information about dynamic parameters, see Cmdlet Dynamic
Parameters.

Input processing methods

The System.Management.Automation.Cmdlet class provides the following virtual


methods that are used to process records. All the derived cmdlet classes must
override one or more of the first three methods:

 System.Management.Automation.Cmdlet.BeginProcessing : Used to
provide optional one-time, pre-processing functionality for the
cmdlet.
 System.Management.Automation.Cmdlet.ProcessRecord : Used to
provide record-by-record processing functionality for the cmdlet.
The System.Management.Automation.Cmdlet.ProcessRecord method
might be called any number of times, or not at all, depending on the
input of the cmdlet.
 System.Management.Automation.Cmdlet.EndProcessing : Used to
provide optional one-time, post-processing functionality for the
cmdlet.
 System.Management.Automation.Cmdlet.StopProcessing: Used to
stop processing when the user stops the cmdlet asynchronously (for
example, by pressing CTRL+C).
For more information about these methods, see Cmdlet Input Processing
Methods.

When you implement a cmdlet, you must override at least one of these input
processing methods. Typically, the ProcessRecord() is the method that you
override because it is called for every record that the cmdlet processes. In
contrast, the BeginProcessing() method and the EndProcessing() method
are called one time to perform pre-processing or post-processing of the records.
For more information about these methods, see Input Processing Methods.

ShouldProcess feature

PowerShell allows you to create cmdlets that prompt the user for feedback
before the cmdlet makes a change to the system. To use this feature, the cmdlet
must declare that it supports the ShouldProcess feature when you declare the
Cmdlet attribute, and the cmdlet must call
the System.Management.Automation.Cmdlet.ShouldProcess and System.Manage
ment.Automation.Cmdlet.ShouldContinue methods from within an input
processing method. For more information about how to support
the ShouldProcess functionality, see Requesting Confirmation.

Transaction

A logical group of commands that are treated as a single task. The task
automatically fails if any command in the group fails, and the user has the
choice to accept or reject the actions performed within the transaction. To
participate in a transaction, the cmdlet must declare that it supports transactions
when the Cmdlet attribute is declared. Support for transactions was introduced
in Windows PowerShell 2.0. For more information about transactions, see How to
Support Transactions.

How Cmdlets Differ from Commands

Cmdlets differ from commands in other command-shell environments in the


following ways:

Cmdlets are instances of .NET classes; they are not stand-alone


executables.
 Cmdlets can be created from as few as a dozen lines of code.
 Cmdlets do not generally do their own parsing, error presentation, or
output formatting. Parsing, error presentation, and output formatting
are handled by the PowerShell runtime.
 Cmdlets process input objects from the pipeline rather than from
streams of text, and cmdlets typically deliver objects as output to the
pipeline.
 Cmdlets are record-oriented because they process a single object at
a time.
Cmdlet Base Classes

Windows PowerShell supports cmdlets that are derived from the following two
base classes.
 Most cmdlets are based on .NET classes that derive from
the System.Management.Automation.Cmdlet base class. Deriving
from this class allows a cmdlet to use the minimum set of
dependencies on the Windows PowerShell runtime. This has two
benefits. The first benefit is that the cmdlet objects are smaller, and
you are less likely to be affected by changes to the PowerShell
runtime. The second benefit is that, if you have to, you can directly
create an instance of the cmdlet object and then invoke it directly
instead of invoking it through the PowerShell runtime.

 The more-complex cmdlets are based on .NET classes that derive


from the System.Management.Automation.PSCmdlet base class.
Deriving from this class gives you much more access to the
PowerShell runtime. This access allows your cmdlet to call scripts, to
access providers, and to access the current session state. (To access
the current session state, you get and set session variables and
preferences.) However, deriving from this class increases the size of
the cmdlet object, and it means that your cmdlet is more tightly
coupled to the current version of the PowerShell runtime.

In general, unless you need the extended access to the PowerShell runtime, you
should derive from the System.Management.Automation.Cmdlet class. However,
the PowerShell runtime has extensive logging capabilities for the execution of
cmdlets. If your auditing model depends on this logging, you can prevent the
execution of your cmdlet from within another cmdlet by deriving from
the System.Management.Automation.PSCmdlet class.

Cmdlet Attributes

PowerShell defines several .NET attributes that are used to manage cmdlets and
to specify common functionality that is provided by PowerShell and that might
be required by the cmdlet. For example, attributes are used to designate a class
as a cmdlet, to specify the parameters of the cmdlet, and to request the
validation of input so that cmdlet developers do not have to implement that
functionality in their cmdlet code. For more information about attributes,
see PowerShell Attributes.

Cmdlet Names

PowerShell uses a verb-and-noun name pair to name cmdlets. For example,


the Get-Command cmdlet included in PowerShell is used to get all the cmdlets
that are registered in the command shell. The verb identifies the action that the
cmdlet performs, and the noun identifies the resource on which the cmdlet
performs its action.

These names are specified when the .NET class is declared as a cmdlet. For
more information about how to declare a .NET class as a cmdlet, see Cmdlet
Attribute Declaration.

Writing Cmdlet Code


This document provides two ways to discover how cmdlet code is written. If you
prefer to see the code without much explanation, see Examples of Cmdlet Code.
If you prefer more explanation about the code, see the GetProc
Tutorial, StopProc Tutorial, or SelectStr Tutorial topics.

Adv Cmdlets

A cmdlet or "Command let" is a lightweight command used in the Windows


PowerShell environment. The Windows PowerShell runtime invokes these
cmdlets at command prompt. You can create and invoke them
programmatically through Windows PowerShell APIs. Following are advanced
usage example of cmdlets.

Sr.No. Cmdlet Type & Description

1 Get-Unique Cmdlet

Get-Unique cmdlet can be used to get the unique objects from a sorted list o
objects.
In this example, we're see the Get-Unique cmdlet in action.

2
Group-Object Cmdlet
Example program to showcase Group-Object Cmdlet.

3 Measure-Object Cmdlet
Measure-Object cmdlet can be used to get the properties of the passed outpu
such as min, max, size, count, line etc.

4 Compare-Object Cmdlet
Compare-Object cmdlet can be used to compare two objects.

5 Format-List Cmdlet
Format-List cmdlet can be used to formats the output as a list of properties where
a property appears on a new line.

6 Format-Wide Cmdlet
Where-Object cmdlet can be used to select objects having particular property
values from the collection of objects that are passed to it.

7
Where-Object Cmdlet
Where-Object cmdlet can be used to select objects having particular property
values from the collection of objects that are passed to it.

8 Get-ChildItem Cmdlet
Get-ChildItem cmdlet can be used to get the items or child items in one or more
specific locations.

9 ForEach-Object Cmdlet
ForEach-Object cmdlet can be used to perform operations on each object of a
collection of objects..

10 Start-Sleep Cmdlet
Start-Sleep cmdlet suspends the activity in a script or session for the particula
period of time.

11 Read-Host Cmdlet
Read-Host cmdlet is used to read from the console.
In these example, we're see the Read-Host cmdlet in action.

12 Select-Object Cmdlet
Select-Object cmdlet is used to select object or its properties.

13 Sort-Object Cmdlet
Sort-Object cmdlet is used to sort object by its properties.

14 Write-Warning Cmdlet
Write-Warning cmdlet is used to write warning messages.

15 Write-Host Cmdlet
Write-Host cmdlet is used to write customized messages.

16 Invoke-Item Cmdlet
Invoke-Item cmdlet is used to perform a default action on specified item

17 Invoke-Expression Cmdlet
Invoke-Expression cmdlet is used to perform a command or expression on loca
computer.

18 Measure-Command Cmdlet
Measure-Command cmdlet is used to meaure the time taken by script o
command.

19 Invoke-History Cmdlet
Invoke-History cmdlet is used to run the command from the current session
which are already run.

20 Add-History Cmdlet
Add-History cmdlet is used to add commands in current history.

21 Get-History Cmdlet
Get-History cmdlet is used to get commands run in current session.

22 Get-Culture Cmdlet
Get-Culture cmdlet is used to get current culture set in windows..

SHORT NOTES SPECIAL VARIABLES AND OPERATORS AND LOOP IN


CONDITIONAL WITH EXAMPLES
POWERSHELL

(a) Special variables

PowerShell Special variables store information about PowerShell.


Represents the last token in the last line received by the session.
Represents the execution status of the last operation. It contains
TRUE if the last operation succeeded and FALSE if it failed.These are
also called automatic variables. Following is the list of automatic
variables –

Operator Description

Represents the last token in the last line


$$
received by the session.

Represents the execution status of the last


$? operation. It contains TRUE if the last
operation succeeded and FALSE if it failed.

Represents the first token in the last line


$^
received by the session.

Represents the full path of the user's home


$HOME
directory.
Represents an object that represents the current
$HOST
host application for PowerShell.

(b) Operators
An operator is a character that can be used in the commands or
expressions. It tells the compiler or interpreter to perform the specific
operations and produce the final result.

PowerShell supports the following different types of operators:

Arithmetic Operators
Arithmetic operators are used to perform numeric calculations. The
operators that are available are available to us in PowerShell are as
follows:
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Remainder: %
- Shift left: -shl
- Shift right: -shr
As well as its use in numeric calculations, the addition operator may
also be used with strings, arrays, and hashtables, and the
multiplication operator may also be used with strings and arrays.

For example
The following scripts demonstrates the arithmetic operators.

> $a = 10

> $b = 20

> $c = 25

> $d = 25
> $a + $b
30

> $a - $b
-10

> $a * $b
200

> $b / $a
2

> $b % $a
0
Assignment Operators
Assignment operators are used to give values to variables. The
assignment operators that are available are as follows:

- Assign: =
- Add and assign: +=
- Subtract and assign: -=
- Multiply and assign: *=
- Divide and assign: /=
- Modulus and assign: %=

As with the arithmetic operators, add and assign may be used with
strings, arrays, and hash tables. Multiply and assign may be used
with strings and arrays.

Example
The following scripts demonstrates the assignment operators.

> $a = 10

> $b = 20

> $c = $a + $b

> $c
30

> $c += $a

> $c
40

> $c -= $a

> $c
30

Comparison Operators
Comparison operators are used for comparing two mathematical
expressions which results in true, false or unknown. PowerShell has a
wide variety of comparison operators which are as follows:
- Equal to and not equal to: -eq and -ne
- Like and not like: -like and -notlike
- Greater than and greater than or equal to: -gt and -ge
- Less than and less than or equal to: -lt and -le
- Contains and not contains: -contains and -notcontains
- In and not in: -in and -notin

Example
The following scripts demonstrates the comparison operators.

> $a = 10

> $b = 20

> $a -eq $b
False

> $a -ne $b
True

> $b -gt $a
True

> $b -ge $a
True

> $b -lt $a
False

> $b -le $a
False

> $a = "mahesh"

> $b = "suresh"

> $a -like '*ahe*'


True

> $a -notLike '*ahe*'


True

> $b -match '[h$]'


True

> $b -notMatch '[h$]'


False

> $a = 'abc'

> $b = 'abc'

> $b -contains $a
True

> $b -notContains $a
False

Logical Operators
The logical operators are used in PowerShell to connect expressions or
statements together to form a single expression. Those expressions
which contain the logical operators usually result in the Boolean
values True or False.
Operator Description Example

Called Logical AND operator. If both the


AND (logical
operands are non-zero, then the condition (A -AND B) is false
and)
becomes true.

Called Logical OR Operator. If any of the two


OR (logical or) operands are non-zero, then the condition (A -OR B) is true
becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand. If a
NOT (logical not) -NOT(A -AND B) is true
condition is true then Logical NOT operator
will make false.

Example
The following scripts demonstrates the logical operators.

> $a = 10

> $b = 20

> $a -AND $b
True
> $a -OR $b
True

> -NOT ($a -AND $b)


False

Redirection Operators
The redirection operators are used in PowerShell to redirect the
output of one command as an input to another command. This
operator describes how to redirect the output from the PowerShell to
the text files.
Operator Description Example

Redirectional operator. Assigns dir >


output to be printed into the test.log
redirected file/output device. will print
>
the
(Redirectiona
directory
l Opeator)
listing in
test.log
file

Example
The following scripts demonstrates the miscellaneous operators.

> $location = Get-Location

> $location -is 'System.Management.Automation.PathInfo'


True

> $location -isNot 'System.Management.Automation.PathInfo'


True

> $i = 1

> $i++

> $i
2

Split and Join Operators


The Split and Join operators are used in PowerShell to divide and
combine the substrings. The Join operator is used to concatenate the
multiple strings into a single string. The split operator is used to split
a string into substrings.

(c) Looping conditions


Loops may be used to iterate through collections, performing an
operation against each element in the collection, or to repeat an
operation (or series of operations) until a condition is met

foreach
The foreach loop executes against each element of a collection using
the following
notation:

foreach (<element> in <collection>) {


<body-statements>
}

For example:
the foreach loop may be used to iterate through each of the processes
returned by Get-Process:

foreach ($process in Get-Process) {


Write-Host $process.Name
}

for
The for loop is typically used to step through a collection using the
following notation:

for (<intial>; <exit condition>; <repeat>){


<body-statements>
}

The for loop is most often used to iterate through a collection.

example:
$processes = Get-Process
for ($i = 0; $i -lt $processes.Count; $i++) {
Write-Host $processes[$i].Name
}

do until and do while


do until and do while each execute the body of the loop at least once,
as the condition test is at the end of the loop statement. Loops based
on do until will exit when the condition evaluates to true; loops based
on do while will exit when the condition
evaluates to false.

do loops are written using the following notation:


do {
<body-statements>
} <until | while> (<condition>)
do until is suited to exit conditions that are expected to be positive.
For example, a script might wait for a computer to respond to a ping:

do {
Write-Host "Waiting for boot"
Start-Sleep -Seconds 5
} until (Test-Connection 'SomeComputer' -Quiet -Count 1)

The do while loop is more suitable for exit conditions that are
negative. For example, a loop might wait for a remote computer to stop
responding to a ping:

do {
Write-Host "Waiting for shutdown"
Start-Sleep -Seconds 5
} while (Test-Connection 'SomeComputer' -Quiet -Count 1)

while
As the condition for a while loop comes first, the body of the loop will
only execute if the condition evaluates to true:

while (<condition>) {
<body-statements>
}

A while loop may be used to wait for something to happen. For


example, it might be used to wait for a path to exist:

while (-not (Test-Path $env:TEMP\test.txt -PathType Leaf)) {


Start-Sleep -Seconds 10
}

break and continue


break can be used to end a loop early. The loop in the following
example would continue to 20; break is used to stop the loop at 10:

for ($i = 0; $i -lt 20; $i += 2) {


Write-Host $i
if ($i -eq 10) {
break # Stop this loop
}
}

The continue keyword may be used to move on to the next iteration of


a loop immediately. For example, the following loop executes a subset
of the loop body when the value of the i variable is less than 2:
for ($i = 0; $i -le 5; $i++) {
Write-Host $i
if ($i -lt 2) {
continue # Continue to the next iteration
}
Write-Host "Remainder when $i is divided by 2 is $($i % 2)"
}

EXAMPLE THE POWER SHELL ADV FUNCTION WITH THE EXAMPLE

PowerShell advanced functions provide the capability to extend a simple


PowerShell script to a tool which behaves like a native PowerShell cmdlet.
PowerShell advanced functions allow regular scripts to utilize the same set of
features available to native cmdlets.

PowerShell advanced functions are built upon four pillars.

1. Stream Control
2. Parameter Validation
3. Pipeline Binding
4. Safeguards

In the next few sections, we will be discussing these in more detail.

 Stream Control

PowerShell engine provides a number of streams which can be used to send


different messages based on the context.

1.  Output / Success
2. Error
3. Warning
4. Verbose
5. Debug
Depending on the context we can leverage inbuilt cmdlets to write to a specific
stream, for example if we want to write to the verbose stream, we can use
the Write-Verbose cmdlet and so on.

However, just using the right cmdlet is not enough as we can observe in figure
1.

Fig. 1: Regular function trying to use Verbose stream

‌In order for the  -Verbose switch to work we need to change our function and
add CmdletBinding as shown in the following example:

Function Do-SomethingRegular{
[CmdletBinding()]
param(
[String]$Message
)
Write-Verbose "We are going to write the message by the User"
Write-Output $Message
}
Do-SomethingRegular -Message "Hi Mom" -Verbose

The CmdletBinding attribute exposes a number of features provided by


PowerShell engine. It won’t be false to say that CmdletBinding attribute makes
our function advanced. As we can observe in figure 2 now, our function correctly
writes to the verbose stream.
Fig. 2: Adding the CmdletBinding attribute to the function leads to the function
correctly writing to the verbose stream

Next, we look at a more complex example which involves the error stream. We
first need to define the difference between terminating and non-terminating
errors:

 A terminating error is a fatal mistake which will halt the execution of


the program.

 A non-terminating error is less serious and will not result in halting the
execution of the program.

If PowerShell engine encounters a non-terminating error, it first checks the value


of the ErrorActionPreference variable to determine if it should continue or
terminate the execution. By default, this value is set to “continue” which means
that if PowerShell engine encounters an error then it should just continue
processing the rest of the script.

We can observe this behavior in figure 3: when PowerShell engine encounters a


non-terminating error it generates an error message and continues executing
the rest of the script.
Fig. 3: PowerShell engine continues executing the script after encountering a
nonterminating error

But what if we wanted to terminate the script as soon as we encounter the non-
terminating error?
The solution is to modify the value of ErrorActionPreference variable to “Stop”.

However, changing this variable will impact all the other scripts on the system as
well as this is a global variable. The solution is to use the -ErrorAction switch as
shown in figure 4 and tell PowerShell engine to treat our script as if the
“ErrorActionPreference” variable is set to stop. Again, the reason we
have ErrorAction switch available is that we are using advanced functions.
Fig. 4: The ErrorAction switch in combination with the “Stop” option leads to
PowerShell terminating execution when encountering an error

Parameter Validation

Functions are not very useful unless they can accept parameters. Helped
functions are a different story though however our focus is on regular functions.

As such, parameter validation is a very important process before we start using


the supplied parameters into our programming logic. PowerShell engine provides
a number of built-in mechanisms to validate parameters. Advanced functions can
help us leverage this functionality to validate our parameters rather than writing
our own parameter validation logic.

In this section we will discuss some parameter validation techniques however


this list is by no means exhaustive.
1. Mandatory Parameter

Mandatory parameters help to declare certain parameters as required by the


function. If the value is missing, the PowerShell engine will prompt the user for a
value (as shown in figure 5). Here’s an example:

# Writing a function with a mandatory parameter


Function Do-SomethingRegular {
[CmdletBinding]()]
Param(
[Parameter(Mandatory)]
[String] $Message
)
Write-Output $Message
}

# Calling the function


Do-SomethingRegular

Fig. 5: Declaring a parameter as mandatory

2. ValidateScript

ValidateScript can be used to run a script against the supplied parameter value.


If the script returns $true, then the parameter value is accepted. Here’s an
example:
Function Simple-Function {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateScript({Test-Connection -
ComputerName $_ -Quiet -Count 1})]
[string]$computerName
)
$ErrorActionPreference
Get-CimInstance -ClassName win32_Process -ComputerName
$ComputerName
}

Simple-Function -ComputerName 'CAT'

As we can observe in figure 6, we are using ValidateScript to test if we can reach


the machine supplied as ComputerName parameter by the user. The script
uses Test-Connection cmdlet with -Quiet flag to return either true or false. Since
our lab does not have a computer named “CAT” it returns false and validate
script fails to accept the parameter value.

Fig. 6: Validating a PowerShell script with the ValidateScript parameter

3. ValidatePattern

ValidatePattern can be used to validate a parameter value against a regular


expression. Here’s an example:

Function Do-SomethingRegular {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidatePattern('\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.|$)){4}\b')]
[String] $MachineName
)
Get-CimInstance -ComputerName $MachineName -ClassName win32_Process
}
Do-SomethingRegular -MachineName 127.0.01.1

As shown in figure 7 we are validating the supplied value


of MachineName parameter against a regular expression for IP address.

Fig. 7: Validating the supplied value of a parameter against a regular expression

4. ValidateSet

ValidateSet can be used to predefine acceptable values for a parameter (as


shown in figure 8). If the user supplies values other than predefined the function
returns an error. Here’s an example:

Function Do-SomethingRegular{
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateSet('Mom','Dad')]
[String] $Parent
)
Write-Output "Hello " $Parent
}
Do-SomethingRegular -Parent

Fig. 8: Predefining acceptable values for a parameter with ValidateSet

As mentioned earlier PowerShell provides a number of parameter validation


techniques, however, this blog post has only covered some of them. For more
details, read Bruno Buyck’s article on Parameter Validation Concepts in
PowerShell and ScriptRunner, for a complete list please read the official
Microsoft PowerShell documentation.

Pipeline Binding

Parameter pipeline binding is one of the most important concepts in PowerShell.


This section will be only focusing on how to enable parameters to accept Pipeline
input. For more details, visit my other article on Parameter Binding Concepts in
PowerShell.

PowerShell engine binds the pipeline input “by value” or “by property”. Advanced
functions allow us to specify which parameters can accept pipeline input and how
binding should take place.

Let’s take a simple example where we are accepting the pipeline input byValue:

Function Do-SomethingRegular{
[CmdletBinding()]
Param(
[Parameter(Mandatory,valueFromPipeline)]
[String] $name
)
Write-Output "You Entered $name"
}
"Sonny"|Do-SomethingRegular

Figure 9 shows that a string object is passed to our function and since the
function has a parameter accepting value from the pipeline, the functions
executed without any errors.

Fig. 9: Passing a string object as parameter value to a function through the


pipeline

Similarly, we can modify our function to accept pipeline input byProperty:

Function Do-SomethingRegular{
[CmdletBinding()]
Param(

[Parameter(Mandatory,valueFromPipelineByProperty)]
[String] $name
)
Write-Output "You Entered $name"
}
$MyNewObject = [PSCustomObject]@{name = 'Sonny'; age = 21}
$MyNewObject | Do-SomethingRegular

As shown in figure 10, we created an object with a property name matching the
name of our parameter. When this object is passed in the pipeline the
PowerShell engine binds the property with the parameters as they have
matching name.
Fig. 10: Passing a single property of an object as parameter value to a function
through the pipeline

Let’s complicate our example by passing more than one object in the pipeline.
Since we are dealing with multiple objects, we need to utilize Input Processing
methods. Input processing methods are also known as
the BEGIN, PROCESS and END block. A good PowerShell programmer will always
use them when writing an advanced function.

As we can observe in figure 11, even with multiple objects the binding follows
the same principle as our previous example:

Function Do-SomethingRegular{
[CmdletBinding()]
Param(

[Parameter(Mandatory,valueFromPipelineByPropertyName)]
[String] $name
)
process{
Write-Output "You Entered $name"
}
}

$MyNewObject1 = [PSCustomObject]@{name = 'Sonny';age = 21}


$MyNewObject2 = [PSCustomObject]@{name = 'browninfosecguy';age = 21}
$MyNewObject1,$MyNewObject2|Do-SomethingRegular
Fig. 11: Passing one property of multiple objects as parameter values to a
function through the pipeline

Safeguards

PowerShell provides two inbuilt safeguard mechanism.

 WhatIf

 Confirm

These safeguards are controlled by two system


variables $WhatIfPreference and $ConfirmPreference. The default value of both
these variables is shown in figure 12.
Fig. 12: The default value for WhatIf and Confirm Preference variable

WhatIf

The WhatIf switch can be used to see “what would have happened” without


really modifying anything. The behavior is controlled
by $WhatIfPreference variable.
The default value of the $WhatIfPreference is set to false, which is the reason
why when we execute any cmdlet, we are not shown a whatif scenario. In order
to view the whatif scenario we need to explicitly use the whatif switch as shown
in figure 13.

Fig. 13: Example of the -WhatIf switch in PowerShell

Implementing WhatIf functionality in a function can be achieved by:


1. Adding the SupportsShouldProcess argument to CmdletBinding as shown
in figure 14
2. Capturing the Boolean value returned by $PSCmdlet.ShouldProcess(“”), If
TRUE it means user has not selected whatif option
3. Placing whatif logic in an if loop around $PSCmdlet.ShouldProcess(“”)

The following example demonstrates these steps:

Function Delete-Windows{
# First we're adding the “SupportsShouldProcess” argument to CmdletBinding
[CmdletBinding(SupportsShouldProcess)]
param(
)
# Then, we're capturing the Boolean value returned by
“$PSCmdlet.ShouldProcess("")”, If TRUE it means user has not selected whatif
option
if($PSCmdlet.ShouldProcess("Meow")){
Write-Host "WhatIf flag not set, delete
windows"
}
else{
Write-Host "WhatIf flag set, do not delete
windows or real"
}
}

Fig. 14: Implementing WhatIf functionality in a function


 

Confirm

Confirm switch can be used to prompt a user for confirmation before executing


the cmdlet. We can implement the same in our function. As discussed earlier
if $ConfirmPreference variable is set to “high” then the cmdlet’s which have
the ConfirmImpact variable set to “high” will prompt the user for confirmation
before executing.

This brings us another concept, the $ConfirmImpact variable which is used to


define the severity of a function. It can accept the following values:

 “Low”

 “Medium”

 “High”

We can also set it to “None” but that will just disable it.

In order to implement confirm in our function we need to add


the ConfirmImpact argument to CmdletBinding and initiate a value for it. The
PowerShell engine will then compare this value with $ConfirmPreference value
and if the severity of our function is equal or higher, the user will be prompted
with a confirm dialogue. Here’s an example

Function Delete-Windows{
[CmdletBinding(SupportsShouldProcess, ConfirmImpact =
"Medium")]
param(
)
if($PSCmdlet.ShouldProcess("Meow"){
Write-Host "Delete Windows"
}
}

As we can observe in figure 15 since the $ConfirmPreference is set to “High”


PowerShell engine did not prompt the user with confirm dialogue as our function
has a “medium” ConfirmImpact.
Fig. 15: Adding the ConfirmImpact argument to CmdletBinding and setting its
value to “Medium”

‌If we change the $ConfirmPreference value to medium then the user is


prompted with confirm dialogue box as shown in figure 16.

Fig. 16: If $ConfirmPreference value is changed to medium the user is prompted


with confirm dialogue box

Now, what happens if we change back the $ConfirmPreference variable to


“High”? As expected, if we just run Delete-Windows we will not be prompted
with a confirm dialogue box, however if we explicitly use the -Confirm switch
then we will be presented with confirm dialogue box as shown in figure 17.
Fig. 17: Adding the -Confirm switch when calling the function triggers
the confirm dialogue box

EXPLAIN THE POWER SHELL ERROR HANDLING CONCEPT


(TARMINATEING AND NON TERMINATLING )
Error Handling: Expect the Unexpected In a nutshell, error handling is
attempting to code for the unexpected.

PowerShell Error Handling Example

Error handling with PowerShell helps ensure that an unexpected exception does
not let a script continue to cause issues. Let’s take a look at a script that will
make sure only cool people have access to all the cool stuff. (

$GroupMembership = Get-ADGroupMember -Identity "Cool Users"

$UpdatedCoolList = Get-Content \\FileShare\Location\CoolPeople.csv

Foreach($Person in $GroupMembership){

If($UpdatedCoolList -notcontains $Person){

Remove-ADGRoupMember -Identity "Cool Users" -User $Person

}
}

Works great! However, Kris Powell has found out about the cool list, and in
anger at being left off the list, he performs an action that proves we are right to
keep him out. He deletes CoolPeople.csv.

Next time the script runs, we get an exception:

With a blank $UpdatedCoolList variable it removes everyone’s access. Very not


cool Kris.

Exceptions

An exception is an error or unexpected result that PowerShell needs you to


handle.

There are two types of exceptions: terminating and non-terminating.


Terminating exceptions stop the running script. Non-terminating exceptions just
write to the error pipeline.

Making a non-terminating exception a terminating exception is simple. You can


set the command’s parameter to -ErrorAction to stop.

$UpdatedCoolList = Get-Content \\FileShare\Location\CoolPeople.csv -

ErrorAction Stop

You can also set the default action of all errors to stop by setting the
variable $ErrorActionPreference = "Stop".

In most cases, a cmdlet generates a non-terminating exception, but error


handling with PowerShell requires a terminating exception to work.

Try/Catch/Finally

After the -ErrorAction is set to Stop, we can wrap it in a Try/Catch block. Try  is


where we run the command, and Catch  is what will run if it runs into a
terminating error. (See Out-File)

Try {
$UpdatedCoolList = Get-Content \\FileShare\Location\CoolPeople.csv -

ErrorAction Stop

Catch {

$_.Exception | Out-File C:\cool_log\krisdidit.log -Append

Break

In this script-block, we captured the exception and put it in a log file. Break  was
used to exit the script so it would not continue. If we had left the catch block
empty it would absorb the error and continue the script.

The last piece of the error handling with a Try/Catch/Finally block is the Finally.
This is used to provide actions that will always run before exiting the script (or
continuing on). This is mostly used for clean up. You can use it to close database
connections, remove files, or close file locks.  Finally  allows you to revert any
changes done as a result of the script whether an exception is encountered or
not.

WHAT IS OS MODULE? (3 MARKS)

Python - OS Module

It is possible to automatically perform many operating system tasks. The OS


module in Python provides functions for creating and removing a directory
(folder), fetching its contents, changing and identifying the current directory,
etc.

You first need to import the os module to interact with the underlying


operating system. So, import it using the import os statement before using its
functions.

Getting Current Working Directory

The getcwd() function confirms returns the current working directory.

Example: Get Current Working Directory


 Copy
>>> import os
>>> os.getcwd()
'C:\\Python37'
Creating a Directory

We can create a new directory using the os.mkdir() function, as shown below.

Example: Create a Physical Directory


 Copy
>>> import os
>>> os.mkdir("C:\MyPythonProject")

Changing the Current Working Directory

We must first change the current working directory to a newly created one
before doing any operations in it. This is done using the chdir() function. The
following change current working directory to C:\MyPythonProject.

Example: Change Working Directory


 Copy
>>> import os
>>> os.chdir("C:\MyPythonProject") # changing current workign directory
>>> os.getcwd()
'C:\MyPythonProject'

Removing a Directory

The rmdir() function in the OS module removes the specified directory either


with an absolute or relative path. Note that, for a directory to be removed, it
should be empty.

Example: Remove Directory


 Copy
>>> import os
>>> os.rmdir("C:\\MyPythonProject")

List Files and Sub-directories

The listdir() function returns the list of all files and directories in the specified
directory.

Example: List Directories


 Copy
>>> import os
>>> os.listdir("c:\python37")
['DLLs', 'Doc', 'fantasy-1.py', 'fantasy.db', 'fantasy.py', 'frame.py',
'gridexample.py', 'include', 'Lib', 'libs', 'LICENSE.txt', 'listbox.py', 'NEWS.txt',
'place.py', 'players.db', 'python.exe', 'python3.dll', 'python36.dll', 'pythonw.exe',
'sclst.py', 'Scripts', 'tcl', 'test.py', 'Tools', 'tooltip.py', 'vcruntime140.dll',
'virat.jpg', 'virat.py']
EXPLAIN THE HTTP COMMUNICATIONS WITH PYTHON BUILT IN
LIBRARIES?

The http or Hyper Text Transfer Protocol works on client server model. Usually
the web browser is the client and the computer hosting the website is the server.
IN python we use the requests module for creating the http requests. It is a very
powerful module which can handle many aspects of http communication beyond
the simple request and response data. It can handle authentication,
compression/decompression, chunked requests etc.

1. Grequests
GRequests allows you to use Requests with Gevent to make asynchronous HTTP
Requests easily.
Command: pip install grequests
import grequests urls = [ ‘http://www.heroku.com’,
‘http://python-tablib.org’,
‘http://httpbin.org’,
‘http://python-requests.org’,
‘https://yeahhub.com/’
]

2. httplib2
– Comprehensive HTTP client library. The Hypertext Transfer Protocol (HTTP) is
an application protocol for distributed, collaborative, hypermedia information
systems. HTTP is the foundation of data communication for the World Wide Web.
Python httplib2 module provides methods for accessing Web resources via HTTP.
It supports many features, such as HTTP and HTTPS, authentication, caching,
redirects, and compression. Httplib2 is a comprehensive HTTP client library,
httplib2.py supports many features left out of other HTTP libraries. HTTPS
support is only available if the socket module was compiled with SSL support.
Command: pip install httplib2
#!/usr/bin/python3
import httplib2
http = httplib2.Http()
content = http.request(“https://www.yeahhub.com”)[1]
(content.decode())

3. Requests – HTTP Requests for Humans.


Requests allows you to send organic, grass-fed HTTP/1.1 requests, without the
need for manual labor. There’s no need to manually add query strings to your
URLs, or to form-encode your POST data. Keep-alive and HTTP connection
pooling are 100% automatic.
Command: pip install requests
#!/usr/bin/python3
import requests
#GET Request
r = requests.get(‘https://api.github.com/events’)
#POST
Request r = requests.post(‘http://httpbin.org/post’, data = {‘key’:’value’})
4. Treq – Python requests like API built on top of Twisted’s HTTP client

Treq is an HTTP library inspired by requests but written on top of Twisted’s


Agents. It provides a simple, higher level API for making HTTP requests when
using Twisted.

Command: pip install treq

#!/usr/bin/env python
from twisted.internet.task import react
from _utils import print_response
import treq
def main(reactor, *args):
d = treq.get(‘http://httpbin.org/get’)
d.addCallback(print_response)
return d
react(main, [])

5. Urllib3 – A HTTP library with thread-safe connection pooling, file post


support, sanity friendly.

Urllib3 is a powerful, sanity-friendly HTTP client for Python. Much of the Python
ecosystem already uses urllib3 and you should too. urllib3 brings many critical
features that are missing from the Python standard libraries:
Thread safety.
Connection pooling.
Client-side SSL/TLS verification.
File uploads with multipart encoding.
Helpers for retrying requests and dealing with HTTP redirects.
Support for gzip and deflate encoding.
Proxy support for HTTP and SOCKS. 100% test coverage.

Command: pip install urllib3


# Yeahhub.com
from requests.packages
import urllib3 http = urllib3.PoolManager()
r = http.request(‘GET’, ‘https://yeahhub.com’)
print “r.status: “, r.status
print “r.data”, r.data

WHAT ARE THE COMMANDS FOR MANIPULATING FILES AND


DIRECTORIES IN SHELL? (3 MARKS)

cp - copy files and directories

mv - move or rename files and directories

rm - remove files and directories

mkdir - create directories


These four commands are among the most frequently used Linux commands.
They are the basic commands for manipulating both files and directories.

Cp:-The cp program copies files and directories. In its simplest form, it copies a
single file. It can also be used to copy multiple files (and/or directories) to a
different directory.

Mv:-The mv command moves or renames files and directories depending on how


it is used. It will either move one or more files to a different directory, or it will
rename a file or directory. To rename a file, it is used like this. To move files
(and/or directories) to a different directory.

Rm:-The rm command removes (deletes) files and directories.Using the


recursive option (-r), rm can also be used to delete directories.

Mkdir:-The mkdir command is used to create directories. To use it, you simply
type

WHAT ARE THE BASIC VARIABLE OF THE PYTHON? (3 MARKS)


A variable is created the moment we first assign a value to it. A variable is a
name given to a memory location. It is the basic unit of storage in a
program.The value stored in a variable can be changed during program
execution.

Many Values to Multiple Variables:-Python allows you to assign values to


multiple variables in one line .

One Value to Multiple Variables:-And you can assign the same value to
multiple variables in one line.

Global Variables:-Variables that are created outside of a function (as in all of


the examples above) are known as global variables.Global variables can be used
by everyone, both inside of functions and outside.
Local variables are the ones that are defined and declared inside a function.
We can not call this variable outside the function.

WHAT IS THE BLACKLISTS AND WHITELISTS? (3 MARKS)

The blacklisting approach involves defining which entities should be blocked. A


blacklist is a list of suspicious or malicious entities that should be denied access
or running rights on a network or system.The blacklist approach is threat-
centric, and the default is to allow access. Any entity not on the blacklist is
granted access, but anything that’s known or expected to be a threat is blocked.

Whitelisting tackles the same challenges as blacklisting but uses the opposite
approach. Instead of creating a list of threats, you create a list of permitted
entities and block everything else. It’s based on trust, and the default is to deny
anything new unless it’s proven to be acceptable. This results in a much stricter
approach to access control. It’s analogous to denying everyone access to your
office building unless they can pass a background check and have the credentials
to prove that they did.If a firewall only allows particular IP addresses to access a
network, for instance, it’s using the whitelisting approach.

EXPLAIN THE GEOLOCATION ACQUISITION LIBRARY IN PYTHON?

we will discuss on how to get Geolocation when you enter any location name and
its gives all the useful information such as postal code, city, state, country etc.
with the latitudes and the longitudes (the specific coordinates) and vice-versa in
which we provide the coordinates to get the location name. This can be done
using the GeoPy library in python. This library isn’t built into python and hence
needs to be installed explicitly.

Method 1: Getting coordinates from location name


With provided location, it is possible using geopy to extract the coordinates
meaning its latitude and longitude. Therefore, it can be used to express the
location in terms of coordinates.
Approach
Import module
Import Nominatim from geopy- Nominatim is a free service or tool or can be
called an API with no keys that provide you with the data after providing it with
name and address and vice versa. On calling the Nomination tool which accepts
an argument of user_agent you can give any name as it considers it to be the
name of the app to which it is providing its services.
The geocode() function accepts the location name and returns a geodataframe
that has all the details and since it’s a dataframe we can get the address,
latitude and longitude by simply calling it with the given syntax
Syntax: variablename.address
variablename.latitude
variablename.longitude.
# importing geopy library
from geopy.geocoders import Nominatim
# calling the Nominatim tool
loc = Nominatim(user_agent="GetLoc")
# entering the location name
getLoc = loc.geocode("Gosainganj Lucknow")
# printing address
print(getLoc.address)
# printing latitude and longitude
print("Latitude = ", getLoc.latitude, "\n")
print("Longitude = ", getLoc.longitude)

Method 2:
Getting location name from latitude and longitude In this method all the things
are same as the above, the only difference is instead of using the geocode
function we will now use the reverse() method which accepts the coordinates
(latitude and longitude) as the argument, this method gives the address after
providing it with the coordinates.

Syntax:
reverse(latitude,longitude)
Approach
Import module
Call nominatim tool
Pass latitude and longitude to reverse()
Print location name

# importing modules
from geopy.geocoders import Nominatim
# calling the nominatim tool
geoLoc = Nominatim(user_agent="GetLoc")
# passing the coordinates
locname = geoLoc.reverse("26.7674446, 81.109758")
# printing the address/location name
print(locname.address)

WHAT ARE THE CONDITIONAL STATEMENTS PYTHON? (3 MARKS)

If Statement

The If statement is the most fundamental decision-making statement, in which


the code is executed based on whether it meets the specified condition. It has a
code body that only executes if the condition in the if statement is true. The
statement can be a single line or a block of code.

syntax:

if expression
Statement

#If the condition is true, the statement will be executed.

Examples for better understanding:

num = 5
if num > 0:
print(num, "is a positive number.")
print("This statement is true.")
5 is a positive number.
This statement is true.

 If Else Statement


This statement is used when both the true and false parts of a given condition

are specified to be executed. When the condition is true, the statement inside

the if block is executed; if the condition is false, the statement outside the if

block is executed.

 syntax:

 if condition :
#Will executes this block if the condition is true
else :
#Will executes this block if the condition is false

Example for better understanding:

num = 5
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
output : Positive or Zero

If…Elif..else Statement

In this case, the If condition is evaluated first. If it is false, the Elif statement will

be executed; if it also comes false, the Else statement will be executed.

syntax:

if condition :
Body of if
elif condition :
Body of elif
else:
Body of elseExample for better understanding:

We will check if the number is positive, negative, or zero.

num = 7
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
output: Positive number

Nested IF Statement

A Nested IF statement is one in which an If statement is nestled inside another

If statement. This is used when a variable must be processed more than once.

If, If-else, and If…elif…else statements can be used in the program. In Nested If

statements, the indentation (whitespace at the beginning) to determine the

scope of each statement should take precedence.

syntax:

if (condition1):
#Executes if condition 1 is true
if (condition 2):
#Executes if condition 2 is true
#Condition 2 ends here
#Condition 1 ends here

Examples for better understanding:


num = 8
if num >= 0:
if num == 0:
print("zero")
else:
print("Positive number")
else:
print("Negative number")
output: Positive number

Short Hand if statement

Short Hand if statement is used when only one statement needs to be executed

inside the if block. This statement can be mentioned in the same line which

holds the If statement.

The Short Hand if statement in Python has the following syntax:

if condition: statement

Example for better understanding:

i=15
# One line if statement
if i>11 : print (“i is greater than 11″)
The output of the program : “i is greater than 11.”

Short Hand if-else statement

It is used to mention If-else statements in one line in which there is only one

statement to execute in both if and else blocks. In simple words, If you have

only one statement to execute, one for if, and one for else, you can put it all on

the same line.


Examples for better understanding:

#single line if-else statement

a=3
b=5
print("A") if a > b else print("B")
output: B

EXPLAIN THE VI, AND BASIC COMMANDS WITH EXAMPLES

The default editor that comes with the UNIX operating system is called vi
(visual editor). Using vi editor, we can edit an existing file or create a new file
from scratch. we can also use this editor to just read a text file.
Syntax:
vi filename

Modes of Operation in vi editor There are three modes of operation in vi:

 Command Mode: When vi starts up, it is in Command Mode. This


mode is where vi interprets any characters we type as commands and
thus does not display them in the window. This mode allows us to
move through a file, and to delete, copy, or paste a piece of text.
To enter into Command Mode from any other mode, it requires
pressing the [Esc] key. If we press [Esc] when we are already in
Command Mode, then vi will beep or flash the screen.
 Insert mode: This mode enables you to insert text into the file.
Everything that’s typed in this mode is interpreted as input and
finally, it is put in the file. The vi always starts in command mode. To
enter text, you must be in insert mode. To come in insert mode you
simply type i. To get out of insert mode, press the Esc key, which will
put you back into command mode.
 Last Line Mode(Escape Mode): Line Mode is invoked by typing a
colon [:], while vi is in Command Mode. The cursor will jump to the
last line of the screen and vi will wait for a command. This mode
enables you to perform tasks such as saving files, executing
commands.

Starting the vi Editor

There are following way you can start using vi editor :


Commands and their Description
 vi filename:  Creates a new file if it already not exist, otherwise
opens existing file.
 vi -R filename  : Opens an existing file in read only mode.
 view filename  : Opens an existing file in read only mode.
Moving within a File(Navigation):
To move around within a file without affecting text must be in command mode
(press Esc twice). Here are some of the commands can be used to move
around one character at a time.
Commands and their Description
 k  : Moves the cursor up one line.
 j  : Moves the cursor down one line.
 h  : Moves the cursor to the left one character position.
 l  : Moves the cursor to the right one character position.
 0 or |  : Positions cursor at beginning of line.
 $  : Positions cursor at end of line.
 W  : Positions cursor to the next word.
 B  : Positions cursor to previous word.
 (  : Positions cursor to beginning of current sentence.
 )  : Positions cursor to beginning of next sentence.
 H  : Move to top of screen.
 nH  : Moves to nth line from the top of the screen.
 M  : Move to middle of screen.
 L  : Move to bottom of screen.
 nL  : Moves to nth line from the bottom of the screen.
 colon along with x  : Colon followed by a number would position the
cursor on line number represented by x.
Control Commands(Scrolling): There are following useful commands which
can used along with Control Key:
Commands and their Description:
 CTRL+d  : Move forward 1/2 screen.
 CTRL+f  : Move forward one full screen.
 CTRL+u  : Move backward 1/2 screen.
 CTRL+b  : Move backward one full screen.
 CTRL+e  : Moves screen up one line.
 CTRL+y  : Moves screen down one line.
 CTRL+u  : Moves screen up 1/2 page.
 CTRL+d  : Moves screen down 1/2 page.
 CTRL+b  : Moves screen up one page.
 CTRL+f  : Moves screen down one page.
 CTRL+I  : Redraws screen.
Editing and inserting in Files(Entering and Replacing Text): To edit the
file, we need to be in the insert mode. There are many ways to enter insert
mode from the command mode.
 i  : Inserts text before current cursor location.
 I  : Inserts text at beginning of current line.
 a  : Inserts text after current cursor location.
 A  : Inserts text at end of current line.
 o  : Creates a new line for text entry below cursor location.
 O  : Creates a new line for text entry above cursor location.
 r  : Replace single character under the cursor with the next character
typed.
 R  : Replaces text from the cursor to right.
 s  : Replaces single character under the cursor with any number of
characters.
 S  :Replaces entire line.
Deleting Characters: Here is the list of important commands which can be
used to delete characters and lines in an opened file.
 X  Uppercase: Deletes the character before the cursor location.
 x  Lowercase : Deletes the character at the cursor location.
 Dw  : Deletes from the current cursor location to the next word.
 d^  : Deletes from current cursor position to the beginning of the
line.
 d$  : Deletes from current cursor position to the end of the line.
 Dd  : Deletes the line the cursor is on.
Copy and Past Commands: Copy lines or words from one place and paste
them on another place by using the following commands.
 Yy  : Copies the current line.
 9yy  : Yank current line and 9 lines below.
 p  : Puts the copied text after the cursor.
 P  : Puts the yanked text before the cursor.
Save and Exit Commands of the ex Mode : Need to press [Esc] key
followed by the colon (:) before typing the following commands:
 q  : Quit
 q!  : Quit without saving changes i.e. discard changes.
 r fileName  : Read data from file called fileName.
 wq  : Write and quit (save and exit).
 w fileName  : Write to file called fileName (save as).
 w! fileName  : Overwrite to file called fileName (save as forcefully).
 !cmd  : Runs shell commands and returns to Command mode.

WHAT IS SHELL? (3 MARKS)

A shell is special user program which provide an interface to user to use


operating system services. Shell accept human readable commands from
user and convert them into something which kernel can understand. It is
a command language interpreter that execute commands read from
input devices such as keyboards or from files. The shell gets started
when the user logs in or start the terminal.
Shell is broadly classified into two categories –
 Command Line Shell
 Graphical shell

Command Line Shell


Shell can be accessed by user using a command line interface. A special
program called Terminal in linux/macOS or Command Prompt in
Windows OS is provided to type in the human readable commands such
as “cat”, “ls” etc. and then it is being execute.

There are several shells are available for Linux systems like –
 BASH (Bourne Again SHell)  – It is most widely used shell in
Linux systems. It is used as default login shell in Linux systems
and in macOS. It can also be installed on Windows OS.
 CSH (C SHell) – The C shell’s syntax and usage are very similar
to the C programming language.
 KSH (Korn SHell)  – The Korn Shell also was the base for the
POSIX Shell standard specifications etc.

Each shell does the same job but understand different commands and
provide different built in functions.
Why do we need shell scripts
There are many reasons to write shell scripts –
 To avoid repetitive work and automation
 System admins use shell scripting for routine backups
 System monitoring
 Adding new functionality to the shell etc.
Advantages of shell scripts
 The command and syntax are exactly the same as those
directly entered in command line, so programmer do not need
to switch to entirely different syntax
 Writing shell scripts are much quicker
 Quick start
 Interactive debugging etc.
Disadvantages of shell scripts
 Prone to costly errors, a single mistake can change the
command which might be harmful
 Slow execution speed
 Design flaws within the language syntax or implementation
 Not well suited for large and complex task
 Provide minimal data structure unlike other scripting
languages. etc

EXPLAIN THE PYTHON SETUP PROCESS?


Step 1 − Select Version of Python to Install.
Step 2 − Download Python Executable Installer.
Step 3 − Run Executable Installer.
Step 4 − Verify Python is installed on Windows.
Step 5 − Verify Pip was installed.

EXPLAIN THE THE FILE SYSTEM TREE AND ITS NAVIGATION WITH
SHELL COMMANDS? (5 MARKS)
A file system is a logical collection of files on a partition or disk. A partition is a
container for information and can span an entire hard drive if desired.
Your hard drive can have various partitions which usually contain only one file
system, such as one file system housing the /file system or another containing
the / home file system.
One file system per partition allows for the logical maintenance and
management of differing file systems.
Everything in Unix is considered to be a file, including physical devices such as
DVD-ROMs, USB devices, and floppy drives the files on a Linux system are
arranged in what is called a hierarchical directory structure. This means that
they are organized in a tree-like pattern of directories (called folders in other
systems), which may contain files and subdirectories. The first directory in the
file system is called the root directory. The root directory contains files and
subdirectories, which contain more files and subdirectories

Navigation commands

 cat filename:-Displays a filename


 cd dirname:-Moves you to the identified directory
 cp file1 file2:-Copies one file/directory to the specified location
 file filename:-Identifies the file type (binary, text, etc)
 find filename dir:-Finds a file/directory
 head filename:-Shows the beginning of a file
 less filename:-Browses through a file from the end or the
beginning
 ls dirname:-Shows the contents of the directory specified
 mkdir dirname:-Creates the specified directory
 more filename:-Browses through a file from the beginning to the
end
 mv file1 file2:-Moves the location of, or renames a file/directory
 pwd:-Shows the current directory the user is in
 rm filename:-Removes a file
 rmdir dirname:-Removes a directory
 tail filename:-Shows the end of a file
 touch filename:-Creates a blank file or modifies an existing file or
its attributes
 whereis filename:-Shows the location of a file
 which filename:-Shows the location of a file if it is in your PATH

EXPLAIN THE PIL LIBARARY FOR THE IMAGE FORENSIC?

Python Imaging Library


The Python Imaging Library (PIL) adds image processing capabilities to your
Python interpreter. This library supports many file formats, and provides
powerful image processing and graphics capabilities. Pillow is a fork of the
Python Imaging Library (PIL). PIL is a library that offers several standard
procedures for manipulating images. It's a powerful library but hasn't been
updated since 2009 and doesn't support Python 3. Pillow builds on this, adding
more features and support for Python 3. It supports a range of image file
formats such as PNG, JPEG, PPM, GIF, TIFF, and BMP. We'll see how to perform
various operations on images such as cropping, resizing, adding text to images,
rotating, greyscaling, etc., using this library

You might also like