Nested ForEach-Object and Where-Object in PowerShell

MD Aminul Islam Aug 30, 2022
  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
Nested ForEach-Object and Where-Object in PowerShell

Where-Object and ForEach-Object are the two most used cmdlets in PowerShell. The Where-Object works like WHERE, and the ForEach-Object works like FOREACH.

This article will discuss how we can use Where-Object and ForEach-Object for various purposes. Also, we will see necessary examples and explanations to make the topic easier.

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'}

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

Status   Name               DisplayName
------   ----               -----------
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  BFE                Base Filtering Engine
Running  Bonjour Service    Bonjour Service
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  CDPSvc             Connected Devices Platform Service
Running  CDPUserSvc_1505... Connected Devices Platform User Ser...
Running  ClickToRunSvc      Microsoft Office Click-to-Run Service
Running  CoreMessagingRe... CoreMessaging
Running  cplspcon           Intel(R) Content Protection HDCP Se...
Running  CryptSvc           Cryptographic Services
Running  CxAudMsg           Conexant Audio Message Service
Running  CxUtilSvc          CxUtilSvc
Running  DcomLaunch         DCOM Server Process Launcher
Running  Dhcp               DHCP Client
Running  DiagTrack          Connected User Experiences and Tele...
Running  DispBrokerDeskt... Display Policy Service
Running  Dnscache           DNS Client
Running  Dolby DAX2 API ... Dolby DAX2 API Service
Running  DoSvc              Delivery Optimization
Running  DPS                Diagnostic Policy Service
Stopped  DSAService         Intel(R) Driver & Support Assistant
Running  DusmSvc            Data Usage
Stopped  edgeupdate         Microsoft Edge Update Service (edge...
Running  ElevationService   Wondershare Driver Install Service ...
Stopped  ESRV_SVC_QUEENC... Energy Server Service queencreek
Running  EventLog           Windows Event Log
Running  EventSystem        COM+ Event System
Running  FontCache          Windows Font Cache Service
Stopped  gpsvc              Group Policy Client
Running  ibtsiva            Intel Bluetooth Service
Running  igccservice        Intel(R) Graphics Command Center Se...
Running  igfxCUIService2... Intel(R) HD Graphics Control Panel ...
Running  iphlpsvc           IP Helper
Running  LanmanServer       Server
Running  LanmanWorkstation  Workstation
Running  LSM                Local Session Manager
Stopped  MapsBroker         Downloaded Maps Manager
Running  mpssvc             Windows Defender Firewall
Running  NlaSvc             Network Location Awareness
Running  nsi                Network Store Interface Service
Running  OneSyncSvc_1505... Sync Host_1505b45f
Running  Power              Power
Running  ProfSvc            User Profile Service
Running  RasMan             Remote Access Connection Manager
Running  RpcEptMapper       RPC Endpoint Mapper
Running  RpcSs              Remote Procedure Call (RPC)
Running  SamSs              Security Accounts Manager
Running  SAService          Conexant SmartAudio service
Running  Schedule           Task Scheduler
Running  SENS               System Event Notification Service
Running  SgrmBroker         System Guard Runtime Monitor Broker
Running  ShellHWDetection   Shell Hardware Detection
Running  Spooler            Print Spooler
Stopped  sppsvc             Software Protection
Running  stisvc             Windows Image Acquisition (WIA)
Running  StorSvc            Storage Service
Running  SynTPEnhService    SynTPEnh Caller Service
Running  SystemEventsBroker System Events Broker
Stopped  SystemUsageRepo... Intel(R) System Usage Report Servic...
Running  Themes             Themes
Running  TrkWks             Distributed Link Tracking Client
Running  UserManager        User Manager
Running  UsoSvc             Update Orchestrator Service
Running  Wcmsvc             Windows Connection Manager
Running  WinDefend          Microsoft Defender Antivirus Service
Running  Winmgmt            Windows Management Instrumentation
Running  WlanSvc            WLAN AutoConfig
Running  Wondershare Ins... Wondershare Install Assist Service
Running  WpnService         Windows Push Notifications System S...
Running  WpnUserService_... Windows Push Notifications User Ser...
Stopped  WsAppService       Wondershare Application Framework S...
Running  wscsvc             Security Center
Running  WSearch            Windows Search

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}

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


Use Nested ForEach-Object and Where-Object in PowerShell

Below, we shared an example of using both ForEach-Object and Where-Object in nested mode. The code will be something like the following:

$MyArray = ("zoom", "explorer", "edge")
$MyArray | ForEach-Object { get-process | Where-Object ProcessName -EQ $_ | Out-Host }

After running the above line of command, you will get this output:

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
   2054      78    65900     136676      30.17   4496   7 explorer

Please note that the example codes shared here are only executable on the Windows PowerShell environment.

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.


Related Article - PowerShell Object