Nested ForEach-Object and Where-Object in PowerShell

MD Aminul Islam Feb 15, 2024
  1. Use the Where-Object Cmdlet in PowerShell
  2. Use the ForEach-Object Cmdlet in PowerShell
  3. Use Nested ForEach-Object and Where-Object in PowerShell
  4. Use Nested ForEach-Object and Where-Object With if Statements in PowerShell
  5. Conclusion
Nested ForEach-Object and Where-Object in PowerShell

PowerShell’s Where-Object and ForEach-Object cmdlets are indispensable tools for filtering and processing data in a systematic and efficient manner. By harnessing the power of these cmdlets, PowerShell users can manipulate data sets with precision and ease, performing actions based on specific conditions and iterating over collections effortlessly.

This article elucidates the usage of Where-Object and ForEach-Object, demonstrating how they can be employed individually and in conjunction to accomplish various tasks. From filtering Windows services to performing calculations on numerical data and even implementing nested operations for more complex scenarios, these cmdlets offer a robust framework for data manipulation in PowerShell scripting.

Use the Where-Object Cmdlet in PowerShell

The Where-Object is a built-in cmdlet that filters the output command and shows the information you want to see. Generally, the Where-Object works like a filter.

It also allows you to create conditions that can return either true or false.

In the below example, we will find all the services that run on our computer in automatic mode. The command for this purpose is something like the following:

Get-Service | Where-Object -FilterScript { $_.StartType -EQ 'Automatic' }

In this code snippet, we begin by retrieving a collection of Windows services using the Get-Service cmdlet. This collection is then piped to the Where-Object cmdlet, where a filter script is applied to each service object in the pipeline.

Within the filter script, we evaluate the StartType property of each service object to determine if it is equal to the string "Automatic". If a service’s StartType property matches this criteria, it is passed through the pipeline.

This filter script effectively selects only those services that have their startup type set to "Automatic". The result of this filtering operation is a subset of the original service collection, containing only the services configured to start automatically.

After running the above line of command, you will get an output like the one below:

powershell nested foreach-object where-object - output 1

Use the ForEach-Object Cmdlet in PowerShell

The ForEach-Object will let you run a specific task for each object specified. In our example below, we will divide each object by 1024.

The code for our example will be like the following:

3000, 567980, 112432 | ForEach-Object -Process { $_ / 1024 }

In this code snippet, we iterate over a collection of three numbers: 3000, 567980, and 112432 using the ForEach-Object cmdlet. Within the script block, we perform a calculation on each number by dividing it by 1024.

This calculation is executed for each number in the collection individually. As a result, we obtain a new collection containing the results of the division operation, where each number from the original collection has been divided by 1024.

After running the above line of command, you will get an output as shown below:

powershell nested foreach-object where-object - output 2

Use Nested ForEach-Object and Where-Object in PowerShell

The combination of ForEach-Object and Where-Object cmdlets allows for powerful data manipulation and filtering operations. The nested approach, where one cmdlet is used within the scope of another, enhances the capability to process data iteratively and selectively.

This method is particularly useful when dealing with arrays or collections of objects and needing to perform actions based on specific criteria.

Example:

$MyArray = ("python", "explorer", "edge")
$MyArray | ForEach-Object { Get-Process | Where-Object ProcessName -EQ $_ | Out-Host }

In this code snippet, $MyArray contains a list of process names. The ForEach-Object cmdlet iterates over each process name in the array.

Within the script block, Get-Process retrieves information about all running processes, and Where-Object filters these processes based on the condition that their ProcessName property matches the current process name ($_). The filtered process objects are then output to the console using Out-Host.

Output:

powershell nested foreach-object where-object - output 3

Use Nested ForEach-Object and Where-Object With if Statements in PowerShell

In PowerShell scripting, nested if statements provide a way to apply conditional logic within loops and other control structures. When combined with the ForEach-Object and Where-Object cmdlets, nested if statements enable complex data filtering and processing operations.

This method offers flexibility and granularity in handling data based on multiple criteria. It is particularly useful for scenarios where fine-grained control over data manipulation is required.

Example:

$MyArray = @("Value1", "Value2", "Value3")
$MyArray | ForEach-Object {
    if ($_ | Where-Object { $_ -eq "Value1" -or $_ -eq "Value3" }) {
        $_ | Out-Host
    }
}

In this code snippet, $MyArray contains a list of values. The ForEach-Object cmdlet iterates over each value in the array.

Within the nested if statement, Where-Object filters the values based on the condition that they are equal to either "Value1" or "Value3".

If the condition is met, the value is output to the console using Out-Host.

Output:

powershell nested foreach-object where-object - output 4

Conclusion

With its versatile cmdlets such as Where-Object and ForEach-Object, PowerShell empowers users to wield intricate data processing capabilities with finesse. Whether it’s selecting specific elements from a collection, applying conditional logic, or executing tasks on each item iteratively, PowerShell provides the tools necessary to streamline workflow and enhance productivity.

By mastering these cmdlets and understanding their nuances, users can harness the full potential of PowerShell for efficient data manipulation and scripting tasks, unlocking a world of possibilities in automation and administration.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - PowerShell Object