PowerShell Project: Automation Framework
An automation framework is a small script that runs registered tasks in order and logs each result. The task list sets the order, and the log file records what happened.
Register tasks in a list
List the task names in the order they should run. Print the list as one line to check the order.
$tasks = @("Backup", "Clean", "Report")
$tasks -join ", "Run tasks and log each result
Work through the list and add one log line per task. Read the log file back to see the results in order.
$tasks = @("Backup", "Clean")
foreach ($task in $tasks) {
try {
Set-Content -Path ($task + ".txt") -Value "done"
Add-Content -Path "run.log" -Value ($task + ": OK")
} catch {
Add-Content -Path "run.log" -Value ($task + ": FAILED")
}
}
Get-Content -Path "run.log"Keep going after a failed task
A task that fails is caught and logged as failed. The loop then moves on to the next task instead of stopping.
$tasks = @("Good", "Missing")
foreach ($task in $tasks) {
try {
if ($task -eq "Missing") { Get-Item "no-such-file-xyz" -ErrorAction Stop } else { Set-Content -Path ($task + ".txt") -Value "done" }
Add-Content -Path "run.log" -Value ($task + ": OK")
} catch {
Add-Content -Path "run.log" -Value ($task + ": FAILED")
}
}
Get-Content -Path "run.log"Example
$tasks = @("Backup", "Clean", "Report", "Missing")
foreach ($task in $tasks) {
try {
if ($task -eq "Backup") { Set-Content -Path "backup.txt" -Value "backup done" }
elseif ($task -eq "Clean") { Set-Content -Path "clean.txt" -Value "clean done" }
elseif ($task -eq "Report") { Set-Content -Path "report.txt" -Value "report done" }
else { Get-Item "no-such-file-xyz" -ErrorAction Stop }
Add-Content -Path "framework.log" -Value ($task + ": OK")
} catch {
Add-Content -Path "framework.log" -Value ($task + ": FAILED")
}
}
Get-Content -Path "framework.log"Key points
- Task list: A task list is the ordered list of tasks the framework will run.
- Run in order: The framework works through the list from first to last, one task at a time.
- Log file: A log file is a text file that gains one line for each task result.
- Failure handling: A failed task is logged as failed, and the framework keeps going with the next task.
- Result line: Each result line names one task and says whether it passed or failed.
In this example, the task list registers four tasks in order. The loop runs each task in turn and writes one result line to the log file. The last task fails on a missing file, so it is logged as failed, and the log shows all four results in order.
Note
The framework itself stays small, while each task does one small job.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A framework runs four tasks and one fails in the middle. What should the framework do next?