PowerShell日志记录(详细)

时间:2020-05-03 16:12:01

标签: powershell logging logfile 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

我该怎么做? 还有没有可能不必在每个命令后都写“冗长”的字眼?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在此处找到有关 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' }

答案 1 :(得分:0)

这就是manually collect and verify bank accounts的用途。

'将命令输出保存在文件或变量中,并将其向下发送给 管道。”

示例

<#
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更加优雅。

Tee-Object