r/PowerShell • u/ITZ_RAWWW • Sep 15 '26
Script Sharing I made a simple PS Log writer
Hey everyone, I made a simple ps log writer and thought I'd share it. Hopefully it's of use to someone. Just as a quick background, I come from a python background but for work I've been writing a lot of ps for a project I'm working on. Boss man was pleased with the code but then asked about log files (insert spongebob "but what about my drink meme here").
So I did some searching to see if there's a native ps logging module similar to python's. To my dismay, I came across non native options. While they may be reputable, given I work in cybersecurity and I had concerns given the recent uptick in supply chain attacks for open source software i was on edge. Didn't feel like reading through the whole code base to see if it was something that can be trusted. So I just wrote my own really simple version.
If the formatting look odd for some reason below, see my github jist. Hope this helps someone, kind regards!
<#
Author: shewdew the hedgehog
Date: 09/15/2026
Description: PS code to write logs to text file.
Version: Initial
#>
function Write-Log{
<#
Custom function to be able to write basic logs to a text file.
Eventually I might turn this into a whole module and add extended features since I didn't want to downlaod a logging module of the internet. But this works for now.
While not a hard rule, log levels are just like python's:
- Debug
- Info
- Warning
- Error
- Critical
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Level,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Message
)
$timeStamp = Get-Date -Format "dd-MM-yyyy HH:mm:ss"
$logEntry = "$timeStamp - $($level.ToUpper()) - $message"
Add-Content -Path "myLogFile.log" -Value $logEntry
}
function Reset-Log{
# Rotate log file every 90 days
$cutOff = (Get-Date).AddDays(-90)
$file = Get-Item "C:\path\to\myLogFile.log" -ErrorAction Stop
if ($file.LastWriteTime -lt $cutOff) {
Remove-Item $file.FullName -Force
Write-Log -Level "Info" -Message "Log file deleted."
}
}
# Usage
Write-Log -Level "debug" -Message "Succesfully did something or whatever."
Write-Log -Level "Critical" -Message "WEEWOOWEEWOOWEEWOO! SOMETHING BROKE!"
# since the log levels aren't hard coded, you could have a log level of anything lol. Which can be a pro/con.
Write-Log -Level "pizza" -Message "The server blew up..."
22
u/Brasiledo Sep 15 '26
It’s a good foundation and could definitely be reused across multiple scripts. I like this way of creating clean logs
A few recommendations:
Since you already have [CmdletBinding()],
I’d add Write-Verbose $logEntry to take advantage of the built-in -Verbose parameter and optionally output the log entry to the console.
For $Level, you could also add a ValidateSet:
[ValidateSet('Info','Warning','Error')]
[string]$Level
That would prevent invalid log levels from being passed in.
I’d also parameterize $Path so the same function can be reused with a custom log location and filename depending on the script.
7
u/khaffner91 Sep 15 '26
I find it funny that the function date is MM-dd-yyyy, the log lines themselves get dd-MM-yyyy, neither are proper r/ISO8601. We simply use Get-Date -Format "o" so that both humans and systems can understand the timestamps.
5
u/x0n Sep 15 '26
I don't understand your logic. You're deleting the log file if nobody has logged to it for 90 days? Is this your intent? Also, rotating a log means swapping it out with a new one and archiving (zipping, perhaps) the old one. Then, you might want to apply logic to delete archived log files older than N days.
9
u/BlackV Sep 15 '26 edited Sep 15 '26
The irony...
there were a lot of log writers out there that other authors published, but you didn't trust them cause you dont know them or their code
but you want us to trust you and your log writer code, cause reasons ?
heh
I think everyone as some point or other has written their own logging tool, I feel like its a a rite of passage
(write of passage [grin], see what I did there Lee, see what I did there)
fantastic
3
u/A_poet_in_relapse Sep 15 '26
I want to understand so bad but there are SO MANY commands. I feel dumb looking at this log writer :/ any recommendations where to start late in the game?
5
u/MonkeyNin Sep 15 '26
If you want SeverityLevel suggestions to be optional, in Pwsh 7 you can use
[ArgumentCompletions()]verses[ValidateSet()]This gives you tab completions with custom errors
Example use:
Otherwise for Pwsh 5 you need to use ValidateSet or a custom completer
3
u/VeryRareHuman Sep 16 '26
That is very useful logger function. Good for you sharing it here. I will use it.
2
u/BlackV Sep 15 '26 edited Sep 17 '26
questions/suggestions/etc
import-csvyou hard coded your path
you've have reduced your functionality and portability doing this
-path(or-filepathor similar) parameter (default value based on date and temp folder or something)add-contentand the file does not exist?2
u/Twist_and_pull Sep 15 '26
Isnt that cutOff deleting every day older logs than 90 days and not every 90 days?
2
u/DownAndKindaOut Sep 16 '26 edited Sep 17 '26
Seeing that it's already an advanced function, you can use the begin, process and end block + ValueFromPipeline to allow piping messages to the function.
This allows for things like:
"Log message 1", "Log message 2", "Log message 3" | Write-LogYou can save a couple of messages in an array and pipe the array to the log function.
Bonus: Add a passthrough switch that prints the message to the console when specified.
2
u/BXRedGhost Sep 16 '26
Are you going to make it a module? That’s why I like to do so it’s more easily reusable.
1
u/PinchesTheCrab Oct 22 '26
I'd use the format operator and splatting for Add-Content:
0
u/CyberChevalier Sep 16 '26
The reset log is a little bit “hardcore” I would have gone with a regex remove of line older than x days which would have been more elegant
11
u/[deleted] Sep 15 '26
[removed] — view removed comment