When writing larger scripts, logging is a must, so in this post I will share a simple function for logging PowerShell script.
The basic variables:
To begin with, we need to set a few variables, some of these can be removed if you don’t need them or combined.
$fileName = (Get-WmiObject -Class Win32_BIOS | Select-Object SerialNumber).SerialNumber $logFileName = $fileName + ".log" $directoryPath = "C:\Logs" $log = $directoryPath + "\" + $logFileName
$filename: This will take the serial-number of the client, something I prefer to use for tracking scripts on clients. (Exchange this for the computer name for example)
$logFileName: Adds “.log” to the end of $filename
$directoryPath: This is where the log file will be created. (In this example the folder must be present on the system)
$log: Combines all of the above into a single variable.
The function:
When the above is in place, we will be able to use the following function, in my case called “Write-log”
function Write-Log { param( [parameter(Mandatory=$true)] [string]$Text, [parameter(Mandatory=$true)] [ValidateSet("WARNING","ERROR","INFO")] [string]$Type ) [string]$logMessage = [System.String]::Format("[$(Get-Date)] -"),$Type, $Text Add-Content -Path $log -Value $logMessage }
As you can see, we have two mandatory parameters. “Text” and “Type”.
I don’t think I need to explain what these are used for, so moving on.
[string]$logMessage = [System.String]::Format("[$(Get-Date)] -"),$Type, $Text
In the above extract, you can see that we will create a new variable called $logMessage. This variable is set to be a string and will contain the current date followed by the “Type” and “Text”
Then we will add $logMessage to our log file with:
Add-Content -Path $log -Value $logMessage
Usage:
To use the function, all we need to do is to write one of the following three lines, deepening on what we want to log:
- Write-log -Text”This is an Error” -Type ERROR
- Write-log -Text “This is a Warning” -Type WARNING
- Write-log -Text “This is just Information” -Type INFO
If we open the *.log file in notepad, you will see the following:
Not to bad, but the result will be even better if we use CMTrace. As you can see, the all errors will be marked in red, warnings in yellow and info in white.
Conclusion
This is a really simple function and it requires that you write the messages yourself, but it comes in handy if you have other functions or long scripts that you want to trace.
In the future I will show you a more advanced version and other ways to create log files.
Until then, here is a link to more guides: PowerShell Guides