Ведение журнала PowerShell (многословно) - PullRequest
0 голосов
/ 03 мая 2020

Я хочу регистрировать свои скрипты PowerShell. Теперь я обнаружил для себя Verbose paramteter.

Сценарий в настоящее время выглядит следующим образом (пример сценария):

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

Как мне это сделать? Есть ли возможность не писать «многословно» после каждой команды?

Спасибо!

1 Ответ

0 голосов
/ 04 мая 2020

Для этого можно использовать Tee-Object .

'Сохраняет вывод команды в файл или переменную, а также отправляет его по конвейеру.'

Примеры

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

Хотя PSFramework, на который указывает вам Alex_P, более элегантен.

Правильное ведение журнала с помощью PowerShell и модуля PSFramework

...