Just Some Things to Read
Log script name in Powershell
1 November 2020
Earlier this year I wrote a blog about logging in Powershell. I was happy with this but recently I have changed the script a bit. Besides logging the function name I want also to log the name of the Powershell script. In those cases when having the script name was usefull I was using multiple Powershell scripts and it took more time than needed to find the function. And it is more clear to log a bit more information about the caller.
Below the function I changed. You can find the original script in this blog post.
function Write-LogEntry{
[CmdletBinding()]
param(
[Parameter (Mandatory = $True, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$FullLogFile
,
[Parameter (Mandatory = $True, Position = 1)]
[ValidateNotNullOrEmpty()]
[ValidateSet("Information", "Warning", "Error")]
[string]$Severity
,
[Parameter (Mandatory = $True, Position = 2)]
[ValidateNotNullOrEmpty()]
[string]$Message
);
[string]$ps = $(([string]$(Get-PSCallStack)[1].Location).Split(":"))[0];
[string]$cmd = $([string]$(Get-PSCallStack)[1].Command);
if($ps -eq $cmd){
$cmd = "N/A"
};
[pscustomobject]@{
Time = (Get-Date -Format "dd-MM-yyyy HH:mm:ss:ms")
Script = $ps
Function = $cmd
Severity = $Severity
Message = $Message
} | Export-Csv -Path $FullLogFile -Append -NoTypeInformation -Delimiter "," -Encoding UTF8;
};
In short I added the column Script and its value (name of the script) is taken from property Location of Get-PSCallStack.
When function Write-LogEntry is called from a script instead of a function then the column Function is set to N/A.
I don't consider the script itself as a function.
Have fun!