PowerShell Automation Scripts
An automation script is a script that checks a condition and acts on what it finds. It inspects data first and then prints a report and a decision.
Count the log files
Create three log files, then count only the log files. The count is the data the decision uses.
Set-Content -Path "app1.log" -Value "ok"
Set-Content -Path "app2.log" -Value "ok"
Set-Content -Path "app3.log" -Value "ok"
$logs = Get-ChildItem -Filter *.log -File
"Log files: " + $logs.CountRead a fixed status file
Create a status file with a fixed word, then read it back. The report prints that word exactly.
Set-Content -Path "status.txt" -Value "ready"
$status = Get-Content -Path "status.txt"
"Status: " + $statusLet the count choose the decision
With three log files and a threshold of three, the count reaches the threshold. The decision line prints archive.
Set-Content -Path "app1.log" -Value "ok"
Set-Content -Path "app2.log" -Value "ok"
Set-Content -Path "app3.log" -Value "ok"
$logs = Get-ChildItem -Filter *.log -File
if ($logs.Count -ge 3) { "Action: archive" } else { "Action: none" }Example
Set-Content -Path "app1.log" -Value "ok"
Set-Content -Path "app2.log" -Value "ok"
Set-Content -Path "status.txt" -Value "ready"
$logs = Get-ChildItem -Filter *.log -File
$status = Get-Content -Path "status.txt"
"Log files: " + $logs.Count
"Status: " + $status
if ($logs.Count -ge 3) { "Action: archive" } else { "Action: none" }Key points
- Automation script: a script that checks a condition and acts on the result.
- Condition: a test the script uses to choose between two actions.
- Report: a short summary of what the script found.
- Decision line: a final line that states the action the script will take.
- Threshold: a fixed number the script compares a count against to make its decision.
In this example, the script creates two log files and a status file, counts the log files, reads the status, prints a short report, and prints the other decision because two log files are below the threshold of three.
Note
an automation script prints the same report for the same data, so a second run with different data can print a different decision.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A script finds 4 log files and its threshold is 3. What decision does it print?