Write structured audit records
Documentation: Microsoft Learn
A [pscustomobject] literal captures the timestamp and host name along with the action, status, and message supplied by the caller.
The script
Script reader
Inspect before you run
Inspect the script below. It does not run in this browser.
Inspection only — no command has run.
Show reference output
Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
$Action = "Inventory"
$Status = "Healthy"
$Message = "Sample error message"
$Log = "C:\Logs\audit.csv"
[pscustomobject]@{Time= Get-Date;Computer= $env:COMPUTERNAME;Action= $Action;Status= $Status;Message= $Message } | Export-Csv $Log -Append -NoTypeInformation- Stage 1$Action
Positional values or no named parameters - Stage 2Export-Csv
-Append -NoTypeInformation
How it works
A [pscustomobject] literal captures the timestamp and host name along with the action, status, and message supplied by the caller. Export-Csv with -Append adds the row to the file in $Log, and -NoTypeInformation keeps the type comment out of it.
Adapting it
Swap the CSV for ConvertTo-Json piped into Add-Content when the message field can contain commas or line breaks, which CSV handles badly once anything reads the file back.
Requirements
Write access to the log path.
If the result is unexpected
Structured audit records are unreadable or lose nested fields.
Serialization depth, mixed console text and inconsistent object shapes can corrupt the intended record format.
- Inspect a raw record and confirm the serializer receives only the expected object.
Validate the result
A consumer can parse the record and retrieve the required nested fields.
Keep the check reliable
Use a versioned record shape and keep diagnostic output separate from serialized data.