Search code examples
powershelllogginglogfileverbose

PowerShell Logging (verbose)


I want to log my PowerShell scripts. Now I have discovered the Verbose paramteter for myself.

The script currently looks like this (sample script):

try {
    New-Item "D:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose
}
catch {
    Write-Host $Error[0] -ForegroundColor Red
}

The output then looks like this:

VERBOSE: Execute the "Create file" operation for the target "Target: D:\Test.txt".

    Directory: D:\


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       03.05.2020     18:09              0 Test.txt

I want the output to appear in the console and also be written to a log file. The output should look like this:

Console:

VERBOSE: Execute the "Create file" operation for the target "Target: D:\Test.txt".

Log file:

01.01.2020      12:00       Execute the "Create file" operation for the target "Target: D:\Test.txt".

You shouldn't see issues like this.

    Directory: D:\


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       03.05.2020     18:09              0 Test.txt

How do I do that? Is there also a possibility not to have to write a "verbose" after every command?

Thank you!


Solution

  • You can find what official documentation on PSFramework logging exists here:

    https://psframework.org/documentation/documents/psframework/logging.html

    Basically, what you do at the beginning of your script is defining where the logs should go using Set-PSFLoggingProvider, then use Write-PSFMessage to write things. Using a logfile is the most common scenario, but many other targets are supported out of the box (Eventlog, Splunk, Azure Log Analytics and more).

    Let's go with logfile for an example:

    $paramSetPSFLoggingProvider = @{
        Name         = 'logfile'
        InstanceName = 'MyTask'
        FilePath     = 'C:\Logs\TaskName-%Date%.csv'
        Enabled      = $true
    }
    Set-PSFLoggingProvider @paramSetPSFLoggingProvider
    

    With that the logging is enabled and any messages generated will then be written to the file "C:\Logs\TaskName-.csv.

    To write messages, you can now:

    # Default verbose message
    Write-PSFMessage "Hello"
    
    # Visible to user by default
    Write-PSFMessage -Level Host -Message "Alex"
    
    # Add some extra info
    try { 1/0 }
    catch { Write-PSFMessage -Level Warning -Message "Tried to do the impossible" -ErrorRecord $_ -Tag 'failed','impossible' }