homepage
Menu
Open menu
  • Training
    Go one level top Back

    Training

    • Courses

      Build cyber prowess with training from renowned experts

    • Hands-On Simulations

      Hands-on learning exercises keep you at the top of your cyber game

    • Certifications

      Demonstrate cybersecurity expertise with GIAC certifications

    • Ways to Train

      Multiple training options to best fit your schedule and preferred learning style

    • Training Events & Summits

      Expert-led training at locations around the world

    • Free Training Events

      Upcoming workshops, webinars and local events

    • Security Awareness

      Harden enterprise security with end-user and role-based training

    Featured

    Get a Free Hour of SANS Training

    Free Course Demos

    Can't find what you are looking for?

    Let us help.
    Contact us
  • Learning Paths
    Go one level top Back

    Learning Paths

    • By Focus Area

      Chart your path to job-specific training courses

    • By NICE Framework

      Navigate cybersecurity training through NICE framework roles

    • DoDD 8140 Work Roles

      US DoD 8140 Directive Frameworks

    • By European Skills Framework

      Align your enterprise cyber skills with ECSF profiles

    • By Skills Roadmap

      Find the right training path based on critical skills

    • New to Cyber

      Give your cybersecurity career the right foundation for success

    • Leadership

      Training designed to help security leaders reduce organizational risk

    • Degree and Certificate Programs

      Gain the skills, certifications, and confidence to launch or advance your cybersecurity career.

    Featured: Solutions for Emerging Risks

    New to Cyber resources

    Start your career
  • Community Resources
    Go one level top Back

    Community Resources

    Watch & Listen

    • Webinars
    • Live Streams
    • Podcasts

    Read

    • Blog
    • Newsletters
    • White Papers
    • Internet Storm Center

    Download

    • Open Source Tools
    • Posters & Cheat Sheets
    • Policy Templates
    • Summit Presentations
    • SANS Community Benefits

      Connect, learn, and share with other cybersecurity professionals

    • CISO Network

      Engage, challenge, and network with fellow CISOs in this exclusive community of security leaders

  • For Organizations
    Go one level top Back

    For Organizations

    Team Development

    • Why Partner with SANS
    • Group Purchasing
    • Skills & Talent Assessments
    • Private & Custom Training

    Leadership Development

    • Leadership Courses & Accreditation
    • Executive Cybersecurity Exercises
    • CISO Network

    Security Awareness

    • End-User Training
    • Phishing Simulation
    • Specialized Role-Based Training
    • Risk Assessments
    • Public Sector Partnerships

      Explore industry-specific programming and customized training solutions

    • Sponsorship Opportunities

      Sponsor a SANS event or research paper

    Interested in developing a training plan to fit your organization’s needs?

    We're here to help.
    Contact us
  • Talk with an expert
  • Log In
  • Join - it's free
  • Account
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. Month of PowerShell - Using The Grouping Operator (a.k.a. What are all these ()?)
Josh Wright - Headshot - 370x370 2025.jpg
Joshua Wright

Month of PowerShell - Using The Grouping Operator (a.k.a. What are all these ()?)

From the things I wish someone told me when I started with PowerShell department: using the PowerShell grouping operator!

July 20, 2022

#monthofpowershell

When I first started working with PowerShell, commands like this were confusing:

PS C:\temp> (Get-Date -Date ((Get-Date).ToUniversalTime()) -UFormat %s)
1657915725.84934

That's ... more parentheses than I expected.

PowerShell uses parentheses for a few different functions, well-documented online. In this article we'll look at the grouping operator ().

Many languages use parentheses to specify operator precedence in expressions:

PS C:\temp> (3 + 5) * 2
16

When PowerShell sees something inside (), it evaluates that first, then it evaluates the remainder of the expression. This is pretty intuitive, since we use it for lots of math equations too. The grouping operator works the same way: statements inside the parentheses are executed first (within the current statement in the pipeline).

Let's look at a practical example.

A Grouping Operator Example

I have two image files with similar file names. File size and date/time are a match too, but I want to know if the files are exactly the same. This is a job for Get-FileHash:

PS C:\temp> Get-ChildItem


Directory: C:\temp


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 7/15/2022 8:01 PM 453684 IMG_3306 copy.jpg
-a---- 7/15/2022 8:01 PM 453684 IMG_3306.jpg


PS C:\temp> Get-FileHash .\IMG_3306.jpg

Algorithm Hash Path
--------- ---- ----
SHA256 41F6DDF12CA703FCB428ED8FF702130613A905DE297FB5EBB577A06CC394C440 C:...


PS C:\temp> Get-FileHash '.\IMG_3306 copy.jpg'

Algorithm Hash Path
--------- ---- ----
SHA256 9A239588772945419F4D6BBC3DDBF870A60A30C028269B6FF5D20EF4E3A8D357 C:...

We see that the different SHA256 hashes indicates that the files are not the same, but what if we wanted to test this condition in a script? We could do something like this:

PS C:\temp> $hash1 = Get-FileHash .\IMG_3306.jpg
PS C:\temp> $hash2 = Get-FileHash '.\IMG_3306 copy.jpg'
PS C:\temp> $hash1.Hash -EQ $hash2.Hash
False

By declaring the Get-FileHash output as variables, we can access the Hash property for each file and test if they are equal using the PowerShell -Eq operator. The hash values are different, so we get the False result.

This approach is fine, and in a script it's perfectly legible, but it declared two variables, $hash1 and $hash2. This is not necessary, since we can use the grouping operator instead:

PS C:\temp> (Get-FileHash IMG_3306).Hash -EQ (Get-FileHash '.\IMG_3306 copy.jpg').Hash
False

In this example we surround the Get-FileHash steps in parentheses, and access the Hash property using dot notation. PowerShell processes the expressions from left to right, executing the statements within the parentheses first before accessing the Hash property and comparing the two values with -EQ.

Statements inside the parentheses are executed first (within the current statement in the pipeline).

Variable Declaration Unnecessary

Once you get the hang of using the grouping operator, you start to realize you don't need to declare variables to access the properties or methods of a PowerShell command. For example, all PowerShell arrays have a property called Count which is the number of elements in the array. You can access this value with any command that returns an array type:

PS C:\temp> Get-ChildItem


Directory: C:\temp


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 7/15/2022 8:01 PM 453684 IMG_3306 copy.jpg
-a---- 7/15/2022 8:01 PM 453684 IMG_3306.jpg


PS C:\temp> (Get-ChildItem).Count
2

In my part 4 article on working with the event log I used an example where I counted the number of event logs available on Windows:

PS C:\temp> (Get-WinEvent -ListLog *).Count
442

Using the grouping operator we can execute the specified command (Get-WinEvent -Listlog *), then access a member property using dot notation. Neat!

When we work with dates, we use a special object type for date and time data. In PowerShell, it's common to identify the object type using the grouping operator and the GetType() method:

PS C:\Temp> Get-Date

Saturday, July 16, 2022 10:42:03 AM


PS C:\Temp> (Get-Date).GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType

Here we see the type is DateType. We can use Get-Member to identify the properties and methods available for a DateType object:

PS C:\Temp> Get-Date | Get-Member


TypeName: System.DateTime

Name MemberType Definition
---- ---------- ----------
Add Method datetime Add(timespan value)
AddDays Method datetime AddDays(double value)
AddHours Method datetime AddHours(double value)
AddMilliseconds Method datetime AddMilliseconds(double value)
AddMinutes Method datetime AddMinutes(double value)
AddMonths Method datetime AddMonths(int months)
AddSeconds Method datetime AddSeconds(double value)
AddTicks Method datetime AddTicks(long value)
AddYears Method datetime AddYears(int value)
CompareTo Method int CompareTo(System.Object value), int CompareTo(dat...
Equals Method bool Equals(System.Object value), bool Equals(datetim...
GetDateTimeFormats Method string[] GetDateTimeFormats(), string[] GetDateTimeFo...
GetHashCode Method int GetHashCode()
...

Let's say you want to get a date/time for 2 days from now. You can use the grouping operator to invoke Get-Date, then call the AddHours() method:

PS C:\temp> (Get-Date).AddHours(48)

Monday, July 18, 2022 10:47:19 AM

Remember, statements inside the parentheses are executed first. Here, Get-Date is executed first, which returns a DateType object. The 48 inside of the next set of parentheses is also evaluated, but since it's a literal and not an expression nothing is executed. Then the result of calling Get-Date (the DateType object) is used to invoke the AddHours() method.

You could have accomplished this same task (getting the date/time 2 days from now) using variables instead:

PS C:\temp> $now = Get-Date
PS C:\temp> $twodaysfromnow = $now.AddHours(48)
PS C:\temp> $twodaysfromnow

Monday, July 18, 2022 10:51:48 AM

This is is also fine. PowerShell purists may point out that this solution declares an unnecessary variable, but it is a perfectly acceptable way of solving the problem at hand.

It's not always necessary to declare a variable, but it can improve legibility. Do what looks best for you.

Simpler Differential Analysis

In my article on threat hunting with PowerShell differential analysis I showed how you can build a baseline of configuration data for a system in a known-good state, then compare the current state of a system under investigation to identify a threat actor. In my SEC504 class we go a bit further in our analysis of how a Command & Control (C2) framework looks when it migrates into an existing process to hide its presence on the system, but we apply the same differential analysis process.

Let's take a look. First, on Windows I'll get a list of the DLLs associated with the Windows Explorer process, saving the output to explorer-modules-baseline.txt:

PS C:\Temp> Get-Process -name explorer -Module | Select-Object ModuleName | Out-File explorer-modules-baseline.txt
PS C:\Temp> Get-Content .\explorer-modules-baseline.txt -First 10

ModuleName
----------
Explorer.EXE
ntdll.dll
KERNEL32.DLL
KERNELBASE.dll
msvcp_win.dll
ucrtbase.dll
combase.dll

This file has a list of all the DLLs normally associated with the Explorer process. Next, as an attacker I'll use Metasploit Meterpreter as my C2 to migrate to the Explorer process, leaving the initial exploit process and blending in to an otherwise legitimate process:

meterpreter > migrate -N explorer.exe
[*] Migrating from 8268 to 4332...
[*] Migration completed successfully.

Now, I want to use differential analysis to identify if the normal DLL list associated with the Explorer process has changed using Compare-Object. I'll create a new file called explorer-modules-current.txt with the current DLL information:

PS C:\Temp> Get-Process -Name explorer -Module | Select-Object Modulename | Out-File explorer-modules-current.txt
PS C:\Temp>

To use Compare-Object, I need to supply -ReferenceObject and -DifferenceObject arguments. Compare-Object won't read the files directly, but I can use the grouping operator with Get-Content to read the files and return the object data:

PS C:\Temp> Compare-Object -ReferenceObject (Get-Content .\explorer-modules-baseline.txt) -DifferenceObject (Get-Content .\explorer-modules-current.txt)
InputObject SideIndicator
----------- -------------
PSAPI.DLL =>
cdprt.dll =>
Windows.Globalization.dll =>
execmodelclient.dll =>
execmodelproxy.dll =>

These 5 DLLs are added by Metasploit Meterpreter during the migrate operation, a valuable Indicator of Compromise (IoC).

Conclusion

In this article we looked at how the PowerShell grouping operator works. We can use the grouping operator instead of declaring a temporary variable to access an object's properties and methods (e.g., (Get-Date).AddHours(12)), and as a way to eliminate temporary variables (e.g., (Get-FileHash IMG_3306).Hash -EQ (Get-FileHash '.\IMG_3306 copy.jpg').Hash).

Remember: statements inside the parentheses are executed first (within the current statement in the pipeline). Next time you see a confusing PowerShell statement with lots of parentheses, just look to the inner-most parentheses first and work your way out to understand the order of execution. Once you grasp that process, complex PowerShell statements become a lot easier to break down.

-Joshua Wright

Return to Getting Started With PowerShell


Joshua Wright is the author of SANS SEC504: Hacker Tools, Techniques, and Incident Handling, a faculty fellow for the SANS Institute, and a senior technical director at Counter Hack.

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Cote D'ivoire
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Eswatini
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
North Macedonia
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania, United Republic Of
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City State
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Recommended Training

  • SEC660: Advanced Penetration Testing, Exploit Writing, and Ethical Hacking™
  • SEC450: Blue Team Fundamentals: Security Operations and Analysis™
  • SEC599: Defeating Advanced Adversaries - Purple Team Tactics & Kill Chain Defenses™

Tags:
  • Cyber Defense
  • Cybersecurity and IT Essentials

Related Content

Blog
CD_Blog_HowtoautomateinAzure_Part2_2.jpg
Cloud Security, Cyber Defense
March 2, 2023
How to Automate in Azure Using PowerShell - Part 2
In this post, we will discuss automation approaches to mitigating risks identified in Part 1 of the How to Automate in Azure Using PowerShell series.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
CD_Blog_HowtoautomateinAzure_Part1_2.jpg
Cloud Security, Cyber Defense
October 11, 2022
How to Automate in Azure Using PowerShell - Part 1
In this post, we’ll cover how to automate the assessment and reporting of your cloud security configuration opportunities.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
powershell_option_340x340.jpg
Cybersecurity and IT Essentials, Cyber Defense, Offensive Operations, Pen Testing, and Red Teaming
July 31, 2022
Month of PowerShell - Keyboard Shortcuts Like a Boss
Let's look at several keyboard shortcuts to speed up your PowerShell sessions.
Josh Wright - Headshot - 370x370 2025.jpg
Joshua Wright
read more
  • Company
  • Mission
  • Instructors
  • About
  • FAQ
  • Press
  • Contact Us
  • Careers
  • Policies
  • Training Programs
  • Work Study
  • Academies & Scholarships
  • Public Sector Partnerships
  • Law Enforcement
  • SkillsFuture Singapore
  • Degree Programs
  • Get Involved
  • Join the Community
  • Become an Instructor
  • Become a Sponsor
  • Speak at a Summit
  • Join the CISO Network
  • Award Programs
  • Partner Portal
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Cote D'ivoire
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Eswatini
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
North Macedonia
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania, United Republic Of
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City State
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • Privacy Policy
  • Terms and Conditions
  • Do Not Sell/Share My Personal Information
  • Contact
  • Careers
© 2025 The Escal Institute of Advanced Technologies, Inc. d/b/a SANS Institute. Our Terms and Conditions detail our trademark and copyright rights. Any unauthorized use is expressly prohibited.
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn