我想记录我的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"?
谢谢!
您可以在这里找到关于PSFramework日志记录的官方文档:
https://psframework.org/documentation/documents/psframework/logging.html
基本上,您在脚本开始时所做的是使用Set-PSFLoggingProvider
定义日志的位置,然后使用Write-PSFMessage
编写内容。使用日志文件是最常见的场景,但许多其他目标都是开箱即用的(Eventlog、Splunk、Azure日志分析等(。
让我们以日志文件为例:
$paramSetPSFLoggingProvider = @{
Name = 'logfile'
InstanceName = 'MyTask'
FilePath = 'C:LogsTaskName-%Date%.csv'
Enabled = $true
}
Set-PSFLoggingProvider @paramSetPSFLoggingProvider
启用日志记录,然后将生成的任何消息写入文件";C: \Logs\TaskName-.csv.
要编写消息,您现在可以:
# 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' }
这就是Tee对象的用途。
将命令输出保存在文件或变量中,并将其发送到管道。'
示例
<#
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:Test1testfile2.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:testAllSystemFiles.txt" -Append |
Out-File c:testNewSystemFiles.txt
尽管Alex_p为您指出的PSFramework更优雅。
使用PowerShell和PSFramework模块正确完成日志记录