Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

#21 PowerShell Learning: Understanding Parentheses, Braces and Square Brackets

August 20, 2023
in Blog, PowerShell Learning
0
ADVERTISEMENT

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.

5/5 - (1 vote)
Previous Post

Get Properties of an Object in PowerShell without using Parentheses?

Next Post

#22 PowerShell Learning: The Philosophy Verb-Noun

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory