Powershell foreach

The powershell foreach loop must be one of the most powerful tools in any scripting toolkit. It allows you to easily repeat a list of actions multiple times.

below is a classic example that highlights the power of the foreach loop:

$servers = "Srv101","Srv102","Srv103"

foreach ($server in $servers)
     invoke-command -ComputerName $server -ScriptBlock
         Install-WindowsFeature  BitLocker

         New-Item HKLM:SOFTWARE/Policies/Microsoft/FVE
         Set-Location HKLM:SOFTWARE/Policies/Microsoft
         Set-ItemProperty FVE -Name UseAdvancedStartup -Value 1
         Set-ItemProperty FVE -Name EnableBDEWithNoTPM -Value 1

In the above script we effectively install Bitlocker, configure the registry to allow encryption without the use of a TPM chip and reboot the computer to make sure the bit locker install completes properly. On 3 machines using one script!

When using the foreach loop you’ll often be also using arrays, so here are some tips on using arrays:

quick and dirty integer array using simple comma notation:

$myarray = 1,2,3

more elaborate syntax achieving the same result:

$myarray = @(1,2,3)

if you need something more elaborate, then I suggest you look into ConvertFrom-Json which will give you a very powerful way to manage configurations and multiple arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *