PowerShell - Other Concepts

 

Powershell - Special Variables

PowerShell Special variables store information about PowerShell. These are also called automatic variables. Following is the list of automatic variables −

OperatorDescription
$$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.
$_Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.
$ARGSRepresents an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block.
$CONSOLEFILENAMERepresents the path of the console file (.psc1) that was most recently used in the session.
$ERRORRepresents an array of error objects that represent the most recent errors.
$EVENTRepresents a PSEventArgs object that represents the event that is being processed.
$EVENTARGSRepresents an object that represents the first event argument that derives from EventArgs of the event that is being processed.
$EVENTSUBSCRIBERRepresents a PSEventSubscriber object that represents the event subscriber of the event that is being processed.
$EXECUTIONCONTEXTRepresents an EngineIntrinsics object that represents the execution context of the PowerShell host.
$FALSERepresents FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string "false".
$FOREACHRepresents the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable.
$HOMERepresents the full path of the user's home directory.
$HOSTRepresents an object that represents the current host application for PowerShell.
$INPUTRepresents an enumerator that enumerates all input that is passed to a function.
$LASTEXITCODERepresents the exit code of the last Windows-based program that was run.
$MATCHESThe $Matches variable works with the -match and -notmatch operators.
$MYINVOCATION$MyInvocation is populated only for scripts, function, and script blocks. PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script.
$NESTEDPROMPTLEVELRepresents the current prompt level.
$NULL$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
$PIDRepresents the process identifier (PID) of the process that is hosting the current PowerShell session.
$PROFILERepresents the full path of the PowerShell profile for the current user and the current host application.
$PSCMDLETRepresents an object that represents the cmdlet or advanced function that is being run.
$PSCOMMANDPATHRepresents the full path and file name of the script that is being run.
$PSCULTURERepresents the name of the culture currently in use in the operating system.
$PSDEBUGCONTEXTWhile debugging, this variable contains information about the debugging environment. Otherwise, it contains a NULL value.
$PSHOMERepresents the full path of the installation directory for PowerShell.
$PSITEMSame as $_. Contains the current object in the pipeline object.
$PSSCRIPTROOTRepresents the directory from which a script is being run.
$PSSENDERINFORepresents information about the user who started the PSSession, including the user identity and the time zone of the originating computer.
$PSUICULTURERepresents the name of the user interface (UI) culture that is currently in use in the operating system.
$PSVERSIONTABLERepresents a read-only hash table that displays details about the version of PowerShell that is running in the current session.
$SENDERRepresents the object that generated this event.
$SHELLIDRepresents the identifier of the current shell.
$STACKTRACERepresents a stack trace for the most recent error.
$THISIn a script block that defines a script property or script method, the $This variable refers to the object that is being extended.
$TRUERepresents TRUE. You can use this variable to represent TRUE in commands and scripts.

Powershell - Operators

PowerShell provides a rich set of operators to manipulate variables. We can divide all the PowerShell operators into the following groups −

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Redirectional Operators
  • Spilt and Join Operators
  • Type Operators
  • Unary Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

OperatorDescriptionExample
+ (Addition)Adds values on either side of the operator.A + B will give 30
- (Subtraction)Subtracts right-hand operand from left-hand operand.A - B will give -10
* (Multiplication)Multiplies values on either side of the operator.A * B will give 200
/ (Division)Divides left-hand operand by right-hand operand.B / A will give 2
% (Modulus)Divides left-hand operand by right-hand operand and returns remainder.B % A will give 0

The Comparison Operators

Following are the assignment operators supported by PowerShell language −

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

OperatorDescriptionExample
eq (equals)Compares two values to be equal or not.A -eq B will give false
ne (not equals)Compares two values to be not equal.A -ne B will give true
gt (greater than)Compares first value to be greater than second one.B -gt A will give true
ge (greater than or equals to)Compares first value to be greater than or equals to second one.B -ge A will give true
lt (less than)Compares first value to be less than second one.B -lt A will give false
le (less than or equals to)Compares first value to be less than or equals to second one.B -le A will give false

The Assignment Operators

Following are the assignment operators supported by PowerShell language −

Show Examples

OperatorDescriptionExample
=Simple assignment operator. Assigns values from right side operands to left side operand.C = A + B will assign value of A + B into C
+=Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.C += A is equivalent to C = C + A
-=Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.C -= A is equivalent to C = C - A

The Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Show Examples

OperatorDescriptionExample
AND (logical and)Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.(A -AND B) is false
OR (logical or)Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.(A -OR B) is true
NOT (logical not)Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.-NOT(A -AND B) is true

Miscellaneous Operators

Following are various important operators supported by PowerShell language −

Show Examples

OperatorDescriptionExample
> (Redirectional Opeator)Redirectional operator. Assigns output to be printed into the redirected file/output device.dir > test.log will print the directory listing in test.log file


Powershell - Conditions

Decision making structures have one or more conditions to be evaluated or tested by the program, 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 −

Decision Making

PowerShell scripting language provides following types of decision making statements. Click the following links to check their detail.

Sr.No.Statement & Description
1if statement

An if statement consists of a boolean expression followed by one or more statements.

2if...else statement

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

3nested if statement

You can use one if or elseif statement inside another if or elseif statement(s).

4switch statement

switch statement allows a variable to be tested for equality against a list of values.

Powershell - Array

PowerShell provides a data structure, the array, which stores a fixed-size sequential collection of elements of the any type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables or objects.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you can specify the type of array the variable can reference. Here is the syntax for declaring an array variable −

Syntax

$A = 1, 2, 3, 4
or
$A = 1..4  

Note − By default type of objects of array is System.Object. GetType() method returns the type of the array. Type can be passed.

Example

The following code snippets are examples of this syntax −

[int32[]]$intA = 1500,2230,3350,4000

$A = 1, 2, 3, 4
$A.getType()

This will produce the following result −

Output

IsPublic    IsSerial    Name                        BaseType                     
--------    --------    ----                        --------                     
True        True        Object[]                    System.Array 

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −

$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123

Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.

Array myList

Processing Arrays

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example

Here is a complete example showing how to create, initialize, and process arrays −

$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123

write-host("Print all the array elements")
$myList

write-host("Get the length of array")
$myList.Length

write-host("Get Second element of array")
$myList[1]

write-host("Get partial array")
$subList = $myList[1..3]

write-host("print subList")
$subList

write-host("using for loop")
for ($i = 0; $i -le ($myList.length - 1); $i += 1) {
   $myList[$i]
}

write-host("using forEach Loop")
foreach ($element in $myList) {
   $element
}

write-host("using while Loop")
$i = 0
while($i -lt 4) {
   $myList[$i];
   $i++
}

write-host("Assign values")
$myList[1] = 10
$myList

This will produce the following result −

Output

Print all the array elements
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
Get the length of array
10
Get Second element of array
4.5
Get partial array
print subList
4.5
3.3
13.2
using for loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using forEach Loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using while Loop
5.6
4.5
3.3
13.2
Assign values
5.6
10
3.3
13.2
4
34.33
34
45.45
99.993
11123

The Arrays Methods Examples

Here is a complete example showing operations on arrays using its methods

$myList = @(0..4)

write-host("Print array")
$myList

$myList = @(0..4)

write-host("Assign values")
$myList[1]  = 10
$myList

This will produce the following result −

Output

Clear array
Print array
0
1
2
3
4
Assign values
0
10
2
3
4

Powershell - Hashtables

Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys.

This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods.

Declaring hashtable Variables

To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an hashtable variable −

Syntax

$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{} 

Note − Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are added whereas hashtables do not.

Example

The following code snippets are examples of this syntax −

$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}

Print the hashtable.

$hash

Output

Name                           Value    
----                           -----                                                    
ID                             1                                                        
Color                          Blue                                                     
Shape                          Square 

The hashtable values are accessed through the keys.

> $hash["ID"]
 1

Processing Hashtable

Dot notation can be used to access hashtables keys or values.

> $hash.keys
ID
Color
Shape

> $hash.values
1
Blue
Square

Example

Here is a complete example showing how to create, initialize, and process hashtable −

$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}

write-host("Print all hashtable keys")
$hash.keys

write-host("Print all hashtable values")
$hash.values

write-host("Get ID")
$hash["ID"]

write-host("Get Shape")
$hash.Number

write-host("print Size")
$hash.Count

write-host("Add key-value")
$hash["Updated"] = "Now"

write-host("Add key-value")
$hash.Add("Created","Now")

write-host("print Size")
$hash.Count

write-host("Remove key-value")
$hash.Remove("Updated")

write-host("print Size")
$hash.Count

write-host("sort by key")
$hash.GetEnumerator() | Sort-Object -Property key

This will produce the following result −

Output

Print all hashtable keys
ID
Color
Shape
Print all hashtable values
1
Blue
Square
Get ID
1
Get Shape
print Size
3
Add key-value
Add key-value
print Size
5
Remove key-value
print Size
4
sort by key

Name                           Value                                                                                                   
----                           -----                                                                                                   
Color                          Blue                                                                                                    
Created                        Now                                                                                                     
ID                             1                                                                                                       
Shape                          
Square    

Powershell - Regular Expression

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.

Here is the table listing down all the regular expression metacharacter syntax available in PowerShell −

SubexpressionMatches
^Matches the beginning of the line.
$Matches the end of the line.
.Matches any single character except newline. Using m option allows it to match the newline as well.
[...]Matches any single character in brackets.
[^...]Matches any single character not in brackets.
\ABeginning of the entire string.
\zEnd of the entire string.
\ZEnd of the entire string except allowable final line terminator.
re*Matches 0 or more occurrences of the preceding expression.
re+Matches 1 or more of the previous thing.
re?Matches 0 or 1 occurrence of the preceding expression.
re{ n}Matches exactly n number of occurrences of the preceding expression.
re{ n,}Matches n or more occurrences of the preceding expression.
re{ n, m}Matches at least n and at most m occurrences of the preceding expression.
a| bMatches either a or b.
(re)Groups regular expressions and remembers the matched text.
(?: re)Groups regular expressions without remembering the matched text.
(?> re)Matches the independent pattern without backtracking.
\wMatches the word characters.
\WMatches the nonword characters.
\sMatches the whitespace. Equivalent to [\t\n\r\f].
\SMatches the nonwhitespace.
\dMatches the digits. Equivalent to [0-9].
\DMatches the nondigits.
\AMatches the beginning of the string.
\ZMatches the end of the string. If a newline exists, it matches just before newline.
\zMatches the end of the string.
\GMatches the point where the last match finished.
\nBack-reference to capture group number "n".
\bMatches the word boundaries when outside the brackets. Matches the backspace (0x08) when inside the brackets.
\BMatches the nonword boundaries.
\n, \t, etc.Matches newlines, carriage returns, tabs, etc.
\QEscape (quote) all characters up to \E.
\EEnds quoting begun with \Q.

Here is a complete examples showing how to use regex in PowerShell;

Sr.No.Match & Description
1Match Characters

Example of supported regular expression characters.

2Match Character Classes

Example of supported character classes.

3Match Quantifiers

Example of supported quantifiers.

Powershell - Backtick

Backtick (`) operator is also called word-wrap operator. It allows a command to be written in multiple lines. It can be used for new line (`n) or tab (`t) in sentences as well. See the examples below −

Example 1

Get-Service * | Sort-Object ServiceType `
| Format-Table Name, ServiceType, Status -AutoSize

It will become

Get-Service * | Sort-Object ServiceType | Format-Table Name, ServiceType, Status -AutoSize

Verify the output as

Name                                                   ServiceType  Status
----                                                   -----------  ------
MSSQLServerADHelper100                             Win32OwnProcess Stopped
ntrtscan                                           Win32OwnProcess Running
...

Example 2

Use of new line and tab.

> Write-host "Title Subtitle"
Title Subtitle

> Write-host "Title `nSubtitle"
Title 
Subtitle

> Write-host "Title `tSubtitle"
Title   Subtitle

Powershell - Brackets

Powershell supports three types of brackets.

  • Parenthesis brackets. − ()

  • Braces brackets. − {}

  • Square brackets. − []

Parenthesis brackets

This type of brackets is used to

  • pass arguments

  • enclose multiple set of instructions

  • resolve ambiguity

  • create array

Example

> $array = @("item1", "item2", "item3")
 
> foreach ($element in $array) { $element }
item1
item2
item3

Braces brackets

This type of brackets is used to

  • enclose statements

  • block commands

Example

$x = 10

if($x -le 20){
   write-host("This is if statement")
}

This will produce the following result −

Output

This is if statement.

Square brackets

This type of brackets is used to

  • access to array

  • access to hashtables

  • filter using regular expression

Example

> $array = @("item1", "item2", "item3")
 
> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }
item1
item2
item3
 
>Get-Process [r-s]*
 Handles    NPM(K)     PM(K)    WS(K)   VM(M)   CPU(s)     Id    ProcessName
-------    ------     -----     -----   -----   ------     --    -----------  
    320        72     27300     33764    227     3.95    4028    SCNotification 
   2298        77     57792     48712    308             2884    SearchIndexer
   ...

Powershell - Alias

PowerShell alias is another name for the cmdlet or for any command element.

Creating Alias

Use New-Alias cmdlet to create a alias. In the below example, we've created an alias help for Get-Help cmdlet.

 New-Alias -Name help -Value Get-Help  

Now invoke the alias.

 help Get-WmiObject -Detailed  

You will see the following output.

NAME
   Get-WmiObject
    
SYNOPSIS
   Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes.    
    
SYNTAX
   Get-WmiObject [
...

Getting Alias

Use get-alias cmdlet to get all the alias present in current session of powershell.

 Get-Alias

You will see the following output.

CommandType     Name                     Definition
-----------     ----                     ----------  
Alias           %                        ForEach-Object
Alias           ?                        Where-Object
Alias           ac                       Add-Content
Alias           asnp                     Add-PSSnapIn 
...

Comments

Popular posts from this blog

Terraform

Scrum Master Interview help - Bootcamp

Kubernetes