Alex
Alex

Reputation: 155

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!

Upvotes: 1

Views: 4345

Answers (2)

Fred
Fred

Reputation: 61

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' }

Upvotes: 1

postanote
postanote

Reputation: 16086

This is what the Tee-Object can be used for.

'Saves command output in a file or variable and also sends it down the pipeline.'

Examples

<#
Example 1: Output processes to a file and to the console
This example gets a list of the processes running on the computer and sends the result to a file. Because a second path is not specified, the processes are also displayed in the console.
#>

Get-Process | 
Tee-Object -FilePath "C:\Test1\testfile2.txt"


Example 2: Output processes to a variable and `Select-Object`

This example gets a list of the processes running on the computer, saves them to the $proc variable, and pipes them to Select-Object.
#>

Get-Process notepad | 
Tee-Object -Variable proc | 
Select-Object processname,handles


<#
Example 3: Output system files to two log files

This example saves a list of system files in a two log files, a cumulative file and a current file.
#>

Get-ChildItem -Path D: -File -System -Recurse |
Tee-Object -FilePath "c:\test\AllSystemFiles.txt" -Append |
Out-File c:\test\NewSystemFiles.txt

Though the PSFramework that Alex_P is pointing you to is more elegant.

Logging Done Right with PowerShell and the PSFramework Module

Upvotes: 1

Related Questions