PowerShell For Each Loop Examples


If you want to iterate over a collection of items in PowerShell, you can make use of the ForEach-Object cmdlet.

Syntax:

ForEach-Object
            [-InputObject ]
            [-Begin ]
            [-Process] 
            [-End ]
            [-RemainingScripts ]
            [-WhatIf]
            [-Confirm]
            []

Examples: Iterate over an Array of Strings

    $cityNames = @("New York", "Los Angeles", "Chicago", "San Francisco")
    
    # Loop through the array using ForEach-Object
    $cityNames | ForEach-Object {
        Write-Host "$_"
    }
    

    Output:

    New York
    Los Angeles
    Chicago
    San Francisco

Examples: Iterate over an Array of Numbers

    $numbers = @(10, 20, 30, 40, 50)
    
    $numbers | ForEach-Object {
        Write-Host "$_"
    }

    Output:

    10
    20
    30
    40
    50
PowerShell For Loop Example

Read More: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.3

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap