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) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. 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