Skip to main content

When to use [] or {} or ()

Yesterday I posted a question that comes up often in my PowerShell classes on when to use special variables. Today I am going to post another one. When to open and close code and what characters to use.

Indexes of Arrays [ ]

The Square braces are used when we want to access an element of an array, also known as a collection.

# Accessing Array Elements

 

# Create an array.

$Fruit = "Apple", "Grape", "Orange", "Pear"

 

# Access the first element of the array using index 0.

$Fruit[0]

 

# Access the second element of the array using index 1.

$Fruit[1]

 

# Access the last element in an array using -1.

$Fruit[-1]

 

# Access the last element in an array using -2.

$Fruit[-2]

OK, that was easy. Not so for the next two.

 

Using Script Blocks { }

The curly braces are used with script blocks. A script block allows you to take multiple lines of code and use them as a single unit. Many commands can utilize script blocks. Script Blocks are used when declaring functions, classes, workflows, enums, hash tables, and DSC. They are also used in cmdlets with parameters such as ScriptBlock, Begin, Process, and End. Also IF and SWITCH statements use them.  The help files of cmdlets will guide you in how to use them. Here are a few examples.

# ScriptBlock used in a functions

Function MyFunction

{

    Write-Host "Hello"

}

 

# ScriptBlock used in a remote command

Invoke-Command -ComputerName DC2 -ScriptBlock {Get-Process}

 

# ScriptBlock used in the pipeline with ForeEach-Object

Get-Process |

    ForEach-Object -Process {$_ | Select-Object -ExpandProperty Name}

 

Using Parenthesis ( )

Parenthesis can be used in a few different ways. We can use them to control the order of operation of math.

# Parenthesis used to control the order of a math operation

 

4 + 5 * 2

(4 + 5) * 2

We also use them to execute a cmdlet first in order to gain direct access to the object that the cmdlet produces.

# Parenthesis used get immediate access to the object a cmdlet produces

 

Get-Date | Select-Object -ExpandProperty DayOfWeek

(Get-Date).DayOfWeek

When we are going to do a comparison operation, such as for an IF or SWITCH statement, we use parenthesis to denote the comparison operation.

# Parenthesis used in an IF statement

 

If (1 -lt 5) {Write-Host "It Works"}

 

# Parenthesis used in an SWITCH statment

Switch ("PowerShell")

{

    "PowerShell" {Write-Host "PowerShell"}

    "ShellPower" {Write-Host "ShellPower"}

 

}

We also use the parenthesis with the PARAM keyword.

# Parenthesis used with the PARAM keyword

Function MyCode

{

Param ($Num1, $Num2)

    Write-Output ($Num1 + $Num2)

 

}

 

MyCode -Num1 10 -Num2 5

We also use parenthesis with sub expressions.

# Parenthesis in sub expressions

$Procs = Get-Process | Select-Object -First 1

Write-Output "The process name is $Procs.Name"

 

Write-Output "The process name is $($Procs.Name)"

If you are a bit frustrated when all the different ways to use parenthesis, I do not blame you. They are also used in other loop constructs to. It will come down to your knowledge of PowerShell. That will come with time. Remember the help files are there to guide you. Use them. The examples will show you which set of characters to use with each cmdlet or parameter if required.

Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.