ForEach (Loops)

One of the most common types of loops you’ll use in PowerShell is the foreach type of loop.

A foreach loop reads a set of objects (iterates) and completes when it’s finished with the last one.

The collection of objects that are read is typically represented by an array or a hashtable.


Example: This foreach loop iterates all letters in the $letterarray variable then outputs each letter one by one. This will loop four times. The $letter variable becomes the first item in the array.

$letterArray = 'a','b','c','d'
foreach ($letter in $letterArray)
{
  Write-Host $letter
}


Example: Create multiple folders at once using Foreach loop only if the IF statement is true.

#The $name variable will get the content of the file (C:\Script\12)

$file = get-content -path "C:\Script\12.txt" #This is system object array
$filepath = "C:\Script\"  #Contains "Marketing", "IT", "HR"

foreach ($Name in $file){

      if ((Test-Path $file) -eq $false) {

         New-Item -Path $filepath -Name $Name -ItemType Directory

            }else {Directory EXIST!!}
	 }
	
#The results will have all the directory created for each string in the text file. It will iterate for all the content of the file. Folder creation will ONLY execute IF the folders are NOT present.

Example: What if we want to rename the directory created with the previous loop? It will only rename the folders if its present, if not present, it will skip renaming.

foreach ($Name in $file){ 

If ((test-path -path $file -PathType Container) -eq $true){ 

      Rename-Item -Path $Name -NewName "$Name 1"

         }Else{ Write-Output "Directory does NOT exist!" }

}


Alternative way to create ForEach loops:

ForEach loop with Pipeline

#This will display the content of the file. "$_ " is used to reference variable used after pipeline or method
	
	$File | ForEach-Object -Process {
	
		 Write-Output $_
	}

Example: (Test if path exist, if it does not, create folders)
$FolderName | ForEach-Object -Process {

   if ((test-path -Path "$Folderpath\$_") -eq $false){ 

     New-Item -Path $FolderPath -Name $_ -ItemType Directory 

     }else {Write-Output "Folder already exist"}
}

Another way is to use object method: (Fastest and easy)

$File.ForEach(

{Write-Output $_}

)

Example:
# .ForEach (condition){statement} --It uses parentheses
	
$Foldername.ForEach(
	
{if ((test-path -Path "$Folderpath\$_") -eq $false){

        New-Item -Path $FolderPath -Name $_ -ItemType Directory

             }else {Write-Output "Folder already exist"}}
	
)


Troubleshoot:

Parameter cannot be found error:

Resolution: It is missing a parentheses to wrap the test-path parameter. Modify it to (Test-Path -Path “xx”)-eq $false

Leave a comment