PowerShell 日志记录(详细)

PowerShell Logging (verbose)

我想记录我的 PowerShell 脚本。 现在我自己发现了 Verbose 参数。

脚本当前看起来像这样(示例脚本):

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

输出如下所示:

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

我希望输出出现在控制台中并写入日志文件。 输出应如下所示:

控制台:

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

日志文件:

01.01.2020      12:00       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

我该怎么做? 是否还有可能不必在每个命令后都写一个 "verbose"?

谢谢!

这就是 Tee-Object 的用途。

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

例子

<#
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

尽管 Alex_P 指向您的 PSFramework 更优雅。

Logging Done Right with PowerShell and the PSFramework Module

您可以在此处找到有关 PSFramework 日志记录的官方文档:

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

基本上,您在脚本开头所做的是使用 Set-PSFLoggingProvider 定义日志的位置,然后使用 Write-PSFMessage 写入内容。 使用日志文件是最常见的情况,但开箱即用地支持许多其他目标(Eventlog、Splunk、Azure Log Analytics 等)。

让我们以logfile为例:

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

启用日志记录后,生成的任何消息都将写入文件“C:\Logs\TaskName-.csv.

write messages,您现在可以:

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