When I posted my Write-Log function post on reddit, I was glad to share it. In return, I have been given many good advices that I want you to know. Thanks to my fellow powershellers from /r/powershell. As promised, I also added a way to back the logs up and even a Send-Log function to mail the log if needed.
From now on, we have created a practical Write-Log function that gets the job done.
However, we lack some PowerShell features like pipelining for instance. Also we made some concessions about the best practices, and it would be great to make things more reliable. We will also see how to handle parallel jobs.
This is the 3rd part of the Write-Log series, so make sure to give a look at the previous articles.
In the second part of this Write-Log Series, we are going to work with some advanced parameter and take advantage of snippets to use more efficiently this function. Such a function is going to be used in most of our scripts from now on, so we want it to be simple and easy to use.
With the recent release of PowerShell Core v6.0, it has been officialised that Visual Studio Code is the new recommended PowerShell Editor. Of course, you can still use PowerShell ISE to make your scripts, but VSCode comes with some really interesting features that you definitely want to use.
When a sysadmin creates scripts, he sometimes need to know what happened during the execution of the latter. A common way to do so is to log the actions perfomed by the script. Here is a sample of a Write-Log function usage. We will see how to build this Write-Log function. Sample below :
$LogFile = "C:\Logs\Scripts.log"
$MyDir = Get-ChildItem -Path "C:\" -Directory
Write-Log -Path $LogFile -Message "There are $($MyDir.Count) directories in C:\"
if (Test-Connection -ComputerName "MyServer" -Quiet -Count 1) {
Write-Log -Path $LogFile -Message "MyServer responded."
}
else {
Write-Log -Path $LogFile -Message "Can't reach my server." -Level Error
}
There are many reasons to start with PowerShell. On a given day, you will be cross-roads between repeating 27 times the same task and automating it. On another day, you will need to repeat it 2500 times. Here is you chance, you will have to go through scripting. And PowerShell is the answer.