2 minutes
Using ForEach and ForEach-Object
In today’s tech-driven world, system administrators need to harness the power of PowerShell to enhance their workflow efficiency. Let me share a real-world example to illustrate its effectiveness.
At one of my previous jobs, we had a system that synced legal deadlines to Outlook calendars. The former sysadmin used to check each user’s account weekly to ensure synchronization, a task taking over an hour.
However, with PowerShell and the Selenium module, I automated this process. I created a script that logged into each account and recorded any synchronization issues in a file. This script could be run anytime and was eventually set as a scheduled task, freeing up time for other tasks.
Two essential PowerShell cmdlets are ForEach and ForEach-Object. Here’s why they’re invaluable:
ForEach for Sequential Operations
ForEach is ideal for tasks that require a specific order. It processes a collection of objects one after the other.
Consider this snippet from my Write-Bates script. It renames files in a directory for legal documents based on a set prefix and number of leading zeros:
$files = Get-ChildItem -Path <input_folder>
$prefix = "EXA"
$batesPad = "4"
ForEach ($file in $files) {
$currentFileName = $file.Name
$batesPad = $startRange.PadLeft($length, '0')
$newFileName = $prefix + "$batesPad" + "-" + $file.Name
Rename-Item -Path $file.FullName -NewName $newFileName
Write-Host "$($file.Name) renamed to $newFileName"
}
Output: "EXA0001.pdf, EXA0002.pdf, EXA0003.pdf," etc.
ForEach-Object for Parallel Pipeline Operations
ForEach-Object is a game-changer for its ability to directly integrate with the pipeline. It used to be slower than ForEach, but with PowerShell 7’s -Parallel operator, it’s much faster.
I recommend sysadmins using ForEach-Object upgrade to PowerShell 7 for its multithreading capabilities. It significantly improved the speed of my scripts, especially those that leverage executables capable of using multiple threads.
Here’s an example of a script I use for converting FLAC files to 320kbps M4A using QAAC:
Get-ChildItem -Path "C:\Users\evan\FlacFiles" | ForEach-Object -Parallel {
$trackName = Split-Path -Path "$_" -Leaf
& qaac64 "$trackName" -c320 -q2 --copy-artwork --threading
Write-Host "$trackName converted"
}
Output: All files in the directory converted to 320kbps M4A via multithreading.
By leveraging these PowerShell cmdlets, sysadmins can significantly streamline and automate their workflows, leading to improved efficiency and productivity.
359 Words
2022-10-02 00:00