🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Security Auditing

Security auditing is the practice of keeping a written record of important actions so they can be checked later. A good audit trail says what happened, in order, using fixed labels that are easy to search.

Write a labeled log file

Set-Content starts a log file, and Add-Content appends one labeled line per step. The labels stay fixed, so the log reads the same on every run.

Set-Content -Path "audit.txt" -Value "START backup"
Add-Content -Path "audit.txt" -Value "CHECK files"
Add-Content -Path "audit.txt" -Value "DONE backup"
Get-Content -Path "audit.txt"

Count the logged steps

The number of lines in the log is the number of steps recorded. Reading the Count property prints that number alone.

Set-Content -Path "audit.txt" -Value "START backup"
Add-Content -Path "audit.txt" -Value "CHECK files"
Add-Content -Path "audit.txt" -Value "DONE backup"
(Get-Content -Path "audit.txt").Count

Find one kind of entry

Fixed labels make a log searchable. A Where-Object filter with -like picks out only the lines that carry one label.

Set-Content -Path "audit.txt" -Value "START backup"
Add-Content -Path "audit.txt" -Value "CHECK files"
Add-Content -Path "audit.txt" -Value "DONE backup"
Get-Content -Path "audit.txt" | Where-Object { $_ -like "CHECK*" }

Example

Set-Content -Path "audit.txt" -Value "START report"
Add-Content -Path "audit.txt" -Value "CHECK data"
Add-Content -Path "audit.txt" -Value "DONE report"
Get-Content -Path "audit.txt"
"Steps logged: " + (Get-Content -Path "audit.txt").Count

Key points

  • Audit trail: a written record of important actions, kept so the actions can be checked later.
  • Use Add-Content to append one labeled line per action to a log file.
  • Use fixed labels for each step, so the log stays searchable and never depends on the clock.
  • Keep secrets out of the log. Record what was done, never a password or a credential.
  • Read the log back with Get-Content to check that every step was recorded.

In this example, a log file is first started with a START line, and two more labeled lines are appended for the check and the finish. The full log is then read back in order. A closing line prints how many steps were logged, using the line count alone.

Note

This lesson uses plain log files. It never prints a real date, a real time, or a machine name.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What belongs in a security audit log?