PowerShell日志记录(粗体)

问题描述 投票:0回答:1

我想记录我的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"?

谢谢你!我想记录我的PowerShell命令。

powershell logging logfile verbose
1个回答
0
投票

这就是脚本的内容 三通对象 可用于。

'将命令输出保存在文件或变量中,也可以将其发送到管道中。

例子:'将命令输出保存在文件或变量中,还可以将其发送到管道中。

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

使用PowerShell和PSFramework模块进行正确的日志记录。

© www.soinside.com 2019 - 2024. All rights reserved.