Home > Blockchain >  How to Extract the Count Value into a Variable - Used for ForEach Loop
How to Extract the Count Value into a Variable - Used for ForEach Loop

Time:04-28

I need to trap the Count value of 2 into a Count variable - how can I perform this? The idea in this example is to loop continuously until two hotfixes are installed - which means I can perform a service restart.

C:\WINDOWS\system32> Get-HotFix |? installedon -gt 4/13/2022 | Group installedon –NoElement

Count Name                     
----- ----                     
    2 4/14/2022 12:00:00 AM    

CodePudding user response:

Count is a property of the Microsoft.PowerShell.Commands.GroupInfo instances that
Group-Object (a built-in alias of which is group) outputs, so you can simply access the Count property on each object emitted by your pipeline:

$count =
  Get-HotFix | ? installedon -gt 4/13/2022 | Group installedon –NoElement |
    ForEach-Object Count

Note that $count will end up with an array of counts if the Group-Object call resulted in multiple groups.

  • Related