PowerShell Logging Link to heading
Something each script and application should have
Every PowerShell script—whether it’s a one-liner or a full-blown module—benefits from logging. It’s not just about showing messages on the screen. Logging is essential to:
- ✅ Show status / give feedback to the user
- ✅ Keep logs for audits
- ✅ Trace errors effectively in production
Pitfalls Link to heading
❌ Console-only output Link to heading
The default PowerShell logging commands (Write-Host, Write-Verbose, Write-Debug) only display information at runtime. They don’t preserve logs unless you’re using Start-Transcript—which is a brittle and incomplete solution in many cases.
❌ Overriding built-in commands Link to heading
Redefining Write-Debug or similar built-ins leads to unpredictable behavior and script fragility. This might work in one script, but it will break compatibility and confuse future maintainers.
How to Do It Correctly Link to heading
✅ Define your own logging function Link to heading
Choose a consistent command name like Write-Log, Write-DebugLog, or Write-CustomLog. Use this function in all scripts and modules to standardize behavior.
✅ Default implementation should be useful, not minimal Link to heading
A good baseline includes:
- Timestamps (preferably in ISO 8601 format)
- Log levels (INFO, DEBUG, WARN, ERROR)
- Output to file and console
- Folder creation if missing
- Verbosity filtering
This makes your logging usable immediately, even in production scenarios.
✅ Abstract the backend (wrapper pattern) Link to heading
Start with your own function and wrap external logging frameworks (like PSFramework) if needed. This keeps your script logic independent from implementation changes.
function Write-Log {
# your abstraction here
if ($UsePSFramework) {
Write-PSFMessage ...
} else {
# fallback to local logic
}
}
Get in touch
Email me: starttalking@sh-soft.de