You are on page 1of 39

BCAICT-503

POWERSHELL SCRIPTING

MODULE 2 : The PowerShell Pipeline, Scripts and Syntax


Instructor – Gajendra Shrimal
Pipeline ??
• Short description
– Combining commands into pipelines in the PowerShell
• Long description
– A pipeline is a series of commands connected by pipeline
operators (|) (ASCII 124).
– Each pipeline operator sends the results of the preceding
command to the next command.
– The output of the first command can be sent for processing as
input to the second command. And that output can be sent to
yet another command. The result is a complex command chain
or pipeline that is composed of a series of simple commands.
Syntax
• PowerShell
• Command-1 | Command-2 | Command-3
• For example
– Get-Process notepad | Stop-Process

The first command uses the Get-Process cmdlet to get an


object representing the Notepad process. It uses a
pipeline operator (|) to send the process object to
the Stop-Process cmdlet, which stops the Notepad
process.
pipeline example gets the text files in the current directory, selects only the files that are
more than 10,000 bytes long, sorts them by length, and displays the name and length of
each file in a table.

Get-ChildItem -Path *.txt

Get-ChildItem -Path *.txt | | (FileInfo objects for *.txt)


V
Where-Object {$_.length -gt 10000}
Where-Object {$_.length -gt 10000} | | (FileInfo objects for *.txt)
| ( Length > 10000 )
Sort-Object -Property length | V
Sort-Object -Property Length

Format-Table -Property name, length | (FileInfo objects for *.txt)


| ( Length > 10000 )
| ( Sorted by length )
V
Format-Table -Property name, length
| (FileInfo objects for *.txt)
| ( Length > 10000 )
| ( Sorted by length )
| ( Formatted in a table )
V

Name Length
---- ------
tmp1.txt 82920
tmp2.txt 114000
tmp3.txt 114000
Pipe and Sort
The list is sorted alphabetically
◦ according to the process name.
You can sort WS field
◦ According to the memory usage
To do this the user
◦ “pipes” the output of ps
◦ to a second Cmdlet “sort-object”

ps | sort-object WS –descending
Sorting wrt Memory Usage
Filtering & Splitting the Commands
User can filter that
◦ the “powershell” not to be seen in output
 Add a filter
piped Cmdlets can be
◦ split over multiple lines:

ps | where-object –FilterScript
{$_.processname -ne "powershell"}
| sort-object WS –descending
Using pipelines
• Most PowerShell cmdlets are designed to
support pipelines. In most cases, you
can pipe the results of a Get cmdlet to another
cmdlet of the same noun. For example, you can
pipe the output of the Get-Service cmdlet to
the Start-Service or Stop-Service cmdlets.
• Get-Service wmi | Start-Service
• This example pipeline starts the WMI service on
the computer
• For another example, you can pipe the output
of Get-Item or Get-ChildItem within the
PowerShell registry provider to the New-
ItemProperty cmdlet. This example adds a new
registry entry, NoOfEmployees, with a value
of 8124, to the MyCompany registry key.
• Get-Item -Path HKLM:\Software\MyCompany |
New-ItemProperty -Name NoOfEmployees -
Value 8124
• Many of the utility cmdlets, such as Get-
Member, Where-Object, Sort-Object, Group-
Object, and Measure-Object are used almost
exclusively in pipelines. You can pipe any
object type to these cmdlets. This example
shows how to sort all the processes on the
computer by the number of open handles in
each process.
• Get-Process | Sort-Object -Property handles
• You can pipe objects to the formatting, export,
and output cmdlets, such as Format-
List, Format-Table, Export-Clixml, Export-CSV,
and Out-File.
• This example shows how to use the Format-
List cmdlet to display a list of properties for a
process object.
• Get-Process winlogon | Format-List -Property *
Methods of accepting pipeline input
Cmdlets parameters can accept pipeline input in one of two
different ways:
• ByValue: The parameter accepts values that match the
expected .NET type or that can be converted to that type.
– For example, the Name parameter of Start-Service accepts pipeline
input by value. It can accept string objects or objects that can be
converted to strings.
• ByPropertyName: The parameter accepts input only when the
input object has a property of the same name as the parameter.
– For example, the Name parameter of Start-Service can accept objects
that have a Name property. To list the properties of an object, pipe it
to Get-Member.
Filtered
To concatenation symbol
The concatenation symbol (>)
◦ will send the result output file
◦ after the information has been converted to HTML
◦ so that it can then be viewed in a web browser:

ps |
where-object -FilterScript
{$_.processname -ne "powershell"} |
sort-object WS –descending |
convertto-html -property Name,
Displaying in Browser
Find all the processes on a computer that
started today
Get-Process | Where {$_.starttime -ge
[datetime]::today}
Find the processes that use more than 1000
MB of memory and kill them
get-process | where-object { $_.WS -gt
1000MB } | stop-process -whatif
Calculate the number of bytes in the files in a
directory
get-childitem | measure-object -property
length -sum
Defining Variables
PS C:\> $a = 5
PS C:\> $a
5
PS C:\>
Determine Variable
PS C:\> $a.GetType()
Piped Commands
dir | sort LastWriteTime | more
PS C:\WINDOWS> $a = dir | sort
LastWriteTime

PS C:\WINDOWS> $a[0]

PS C:\WINDOWS> $a[1]
Variables
• Short description
– Describes how variables store values that can be used in PowerShell.
• Long description
– You can store all types of values in PowerShell variables. For
example, store the results of commands, and store elements that are
used in commands and expressions, such as names, paths, settings,
and values.
– A variable is a unit of memory in which values are stored. In
PowerShell, variables are represented by text strings that begin with
a dollar sign ($), such as $a, $process, or $my_var.
types of variables in PowerShell
• User-created variables: User-created variables are created and maintained
by the user.
– By default, the variables that you create at the PowerShell command line exist only while
the PowerShell window is open. When the PowerShell windows is closed, the variables
are deleted. To save a variable, add it to your PowerShell profile.
• Automatic variables: Automatic variables store the state of PowerShell.
These variables are created by PowerShell, and PowerShell changes their
values as required to maintain their accuracy.
– For example, the $PSHOME variable stores the path to the PowerShell installation
directory. For more information, a list, and a description of the automatic variables, see 
about_Automatic_Variables.
• Preference variables: Preference variables store user preferences for
PowerShell. These variables are created by PowerShell and are populated
with default values. Users can change the values of these variables.
– For example, the $MaximumHistoryCount variable determines the maximum number of
entries in the session history.
Working with variables
• To create a new variable, use an assignment statement
to assign a value to the variable. You don't have to
declare the variable before using it. The default value
of all variables is $null.
• To get a list of all the variables in your PowerShell
session, type Get-Variable. The variable names are
displayed without the preceding dollar ($) sign that is
used to reference variables.
• $MyVariable = 1, 2, 3
• $Path = "C:\Windows\System32"
• Variables are useful for storing the results of
commands.
– $Processes = Get-Process
– $Today = (Get-Date).DateTime
To display the value of a variable, type the variable
name, preceded by a dollar sign ($).
$MyVariable
$Today
• To delete the value of a variable, use the Clear-Variable cmdlet or
change the value to $null.

• Clear-Variable -Name MyVariable

• $MyVariable = $null
• To delete the variable, use Remove-Variable or Remove-Item.

• Remove-Variable -Name MyVariable

• Remove-Item -Path Variable:\MyVariable


• It is also possible to assign values to multiple variables with
one statement. The following examples assigns the same
value to multiple variables:

• $a = $b = $c = 0
• The next example assigns multiple values to multiple
variables.

• $i,$j,$k = 10, "red", $true # $i is 10, $j is "red", $k is True


• $i,$j = 10, "red", $true # $i is 10, $j is [object[]], Length 2
Types of variables
• You can store any type of object in a variable, including integers, strings,
arrays, and hash tables. And, objects that represent processes, services,
event logs, and computers.
• PowerShell variables are loosely typed, which means that they aren't
limited to a particular type of object. A single variable can even contain a
collection, or array, of different types of objects at the same time.
• The data type of a variable is determined by the .NET types of the values
of the variable. To view a variable's object type, use Get-Member.
$a = 12 # System.Int32 $a = "Word" # System.String $a = 12, "Word" #
array of System.Int32, System.String $a = Get-ChildItem C:\Windows #
FileInfo and DirectoryInfo types
To use cast notation, enter a type name, enclosed in brackets, before the variable name (on the left
side of the assignment statement). The following example creates a $number variable that can
contain only integers, a $words variable that can contain only strings, and a $dates variable that can
contain only DateTime objects.

• [int]$number = 8 $number = "12345" # The string is converted to an integer.


$number = "Hello“
• Cannot convert value "Hello" to type "System.Int32". Error: "Input string was not in
a correct format." At line:1 char:1 + $number = "Hello" + ~~~~~~~~~~~~~~~~~ +
CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException +
FullyQualifiedErrorId : RuntimeException

• [string]$words = "Hello" $words = 2 # The integer is converted to a string. $words


+= 10 # The plus (+) sign concatenates the strings. $words
Output
• 210
Scopes
• Short description
• Explains the concept of scope in PowerShell and shows how
to set and change the scope of elements.
• Long description
• PowerShell protects access to variables, aliases, functions,
and PowerShell drives (PSDrives) by limiting where they can
be read and changed. PowerShell uses scope rules to ensure
that you do not inadvertently change an item that should not
be changed.
The following are the basic rules of scope:
• Scopes may nest. An outer scope is referred to as a parent
scope. Any nested scopes are child scopes of that parent.
• An item is visible in the scope in which it was created and
in any child scopes, unless you explicitly make it private.
• You can declare variables, aliases, functions, and
PowerShell drives for a scope outside of the current scope.
• An item that you created within a scope can be changed
only in the scope in which it was created, unless you
explicitly specify a different scope.
PowerShell Scopes
• PowerShell supports the following scopes:
– Global: The scope that is in effect when PowerShell starts or when you
create a new session or runspace.
Variables and functions that are present when PowerShell starts have been
created in the global scope, such as automatic variables and preference
variables.
The variables, aliases, and functions in your PowerShell profiles are also
created in the global scope. The global scope is the root parent scope in a
session.
– Local: The current scope. The local scope can be the global scope or any
other scope.
– Script: The scope that is created while a script file runs. Only the commands
in the script run in the script scope. To the commands in a script, the script
scope is the local scope.
Parent and Child Scopes
• Inheritance
• A child scope does not inherit the variables, aliases, and
functions from the parent scope. Unless an item is private,
the child scope can view the items in the parent scope.
And, it can change the items by explicitly specifying the
parent scope, but the items are not part of the child scope.
• However, a child scope is created with a set of items.
Typically, it includes all the aliases that have
the AllScope option. This option is discussed later in this
article. It includes all the variables that have
the AllScope option, plus some automatic variables.
• To find the items in a particular scope, use the
Scope parameter of Get-Variable or Get-Alias.

– For example, to get all the variables in the local /


Global scope, type:
– Get-Variable -Scope local
– Get-Variable -Scope global
Scope Modifiers
• A variable, alias, or function name can include any one of the following
optional scope modifiers:
– global: - Specifies that the name exists in the Global scope.
– local: - Specifies that the name exists in the Local scope. The current scope is
always the Local scope.
– private: - Specifies that the name is Private and only visible to the current scope.
– script: - Specifies that the name exists in the Script scope. Script scope is the
nearest ancestor script file's scope or Global if there is no nearest ancestor script
file.
– using: - Used to access variables defined in another scope while running scripts
via cmdlets like Start-Job and Invoke-Command.
– workflow: - Specifies that the name exists within a workflow. Note: Workflows
are not supported in PowerShell v6 and higher.
– <variable-namespace> - A modifier created by a PowerShell PSDrive provider.
<variable-namespace> - A modifier created by a
PowerShell PSDrive provider. Example

Namespace Description
Alias: Aliases defined in the current
scope

Env: Environment variables defined in


the current scope

Function: Functions defined in the current


scope

Variable: Variables defined in the current


scope
Using scope modifiers
• To specify the scope of a new variable, alias,
or function, use a scope modifier.
– The syntax for a scope modifier in a variable is:
$[<scope-modifier>:]<name> = <value>
– The syntax for a scope modifier in a function is:
function [<scope-modifier>:]<name> {<function-
body>}
Examples
• The following command, which does not use
a scope modifier, creates a variable in the
current or local scope:
$a = "one“
• To create the same variable in Compare that to a private variable:
the global scope, use the $private:pVar = 'Private variable' Get-Variable
scope global: modifier: pVar | Format-List *
$global:a = "one" Get-Variable a | Format-List Output
* Name : a
• Output
Description :
Name : a
Value : one
Description :
Visibility : Public
Value : one
Module :
Visibility : Public
Module :
ModuleName :
ModuleName :
Options : None
Options : None Attributes : {}
Attributes : {}

You might also like