Table of Contents
The goal for this post is to demystify the usage of PowerShell brackets for scripters and PowerShell enthusiasts. You can find braces everywhere, in scripts, in the PowerShell help and in simple one-liners. And there are three types. Let’s dive in.
We distinguish three types of brackets:
- Parentheses ()
- Braces {}
- Square Brackets []
Without a doubt, Parentheses are the most used bracket types in PowerShell. That’s why we will cover Parentheses first.
Parentheses ()
As already mentioned, () is the most seen bracket type in PowerShell. You will find it almost everywhere, for example in the PowerShell help examples which are a great source to learn more about PowerShell syntax.
Parentheses – Example 1
Take a look at the following one-liner. Note that the mathematical calculation (substraction) can only be carried out when the result of both statements is already there.
PS P:\> (Get-Date) - (Get-Date -Day 23 -Month 03 -Year 1976)
Days : 17316
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 14961024000000000
TotalDays : 17316
TotalHours : 415584
TotalMinutes : 24935040
TotalSeconds : 1496102400
TotalMilliseconds : 1496102400000
Parentheses – Example 2
The computernames retrieved by Get-Content wrapped with parentheses must be already there when Restart-Computer comes into play.
Restart-Computer -ComputerName (Get-Content -Path C:\computers.txt) -Force
Parentheses – Example 3
When the script has to decide what to do next, the result of Test-Path in line 1 must already be there.
if (test-path "C:\Windows") {
write-host "The folder is present"
} else {
write-host "The folder is not present"
}
Which brings me to the next type of brackets: Braces.
Braces {}
Unlike Parentheses, objects in braces are not executed instantly. They are widely used in scriptblocks. As you can see below, doing some maths with commands in braces is not a good idea.
PS C:\> {Get-Date} - {Get-Date -Day 23 -Month 03 -Year 1976}
Method invocation failed because [System.Management.Automation.ScriptBlock]
does not contain a method named
'op_Subtraction'.
At line:1 char:1
+ {Get-Date} - {Get-Date -Day 23 -Month 03 -Year 1976}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Subtraction:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Objects (Commands, Variables, …) wrapped with braces are widely used in scriptblocks. They are executed when it is their turn.
Braces – Example 1
Let’s pick up our previous example again, in order to see the difference between () and {}.
if (test-path "C:\Windows") {
write-host "The folder is present"
} else {
write-host "The folder is not present"
}
Test-Path in line 1 is executed instantly. The script blocks from line 2 to 5 are executed when the condition is met, that means on the other hand that they are not executed when the condition is not met.
Braces – Example 2
The command in this example creates a scheduled job on the remote computer AzMember01. Pay attention to the braces.
Invoke-Command -ComputerName HR-PC001 {
Register-ScheduledJob -Name RestartHR-PC001 -ScriptBlock {Restart-Computer -Force} `
-Trigger (New-JobTrigger -Once -At 05:15pm)
}
Several commands are wrapped with Braces. The statement is not executed instantly, because it makes no sense to do anything at first. The PowerShell engine must first examine the entire command to then be able to meaningfully decide what should be done.
Which brings me to the last part.
Square Brackets []
Square brackets retrieve elements in arrays or hashtables and serve as optional parameters.
Square Brackets – Example 1
For instance, let’s say we have an array.
$array=[array]('Peter','Margit','Patrick')
To retrieve array elements, use Square Brackets.
PS C:\> $array=[array]('Peter','Margit','Patrick')
PS C:\> $array[0]
Peter
PS C:\> $array[1]
Margit
PS C:\> $array[1..2]
Margit
Patrick
Square Brackets – Example 2
To get only services beginning with either letter r or s, you need to put r and s in Square Brackets.
PS C:\> Get-Service [rs]* | Select-Object Name,Status
Name Status
---- ------
RasAuto Stopped
RasMan Running
RemoteAccess Stopped
RemoteRegistry Stopped
RetailDemo Stopped
RmSvc Running
...
Last but not least, an example that queries and displays all services which names ends with s or r.
PS C:\> Get-Service *[sr] | Select-Object Status,Name
Status Name
------ ----
Stopped AJRouter
Stopped AppReadiness
Running AudioEndpointBuilder
Stopped BITS
Running CoreMessagingRegistrar
Stopped DevQueryBroker
Running DPS
...
Square Brackets – Example 3
A hashtable is like an array, but it uses a key-value pair.
$hash=@{Kevin = '1'; Alex= '9'; Margit= '12'}
Now we access the key using Square Brackets and get the its value.
PS C:\> $hash=@{Kevin = '1'; Alex= '9'; Margit= '12'}
PS C:\> $hash['Kevin']
1
PS C:\> $hash['Margit']
12
I hope this article has helped to better understand the topic around brackets in PowerShell. All three bracket types were covered. I also hope that the examples are useful and that you can build on them.