Write-Information не отображается в файле, транскрибированном Start-Transcript - PullRequest
1 голос
/ 16 марта 2019

Я использую PowerShell 5.1 и пытаюсь определить, почему сообщения Write-Information не отображаются в журнале расшифровки, созданном Start-Transcript, если я не установил $InformationPreference на SilentlyContinue. Я хочу, чтобы оба сообщения отображались в консоли и , чтобы они записывались в файл журнала.

Я посмотрел здесь: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-5.1#informationpreference

Тогда я решил создать этот скрипт, чтобы проверить, что и когда будет написано. См. Раздел настроек ниже Testing explicit behavior with transcripts -------------

Clear-Host

$ErrorActionPreference = "Stop"

try {
    Write-Host "Starting transcript"
    Start-Transcript -Force -Path "$PSScriptRoot\default.txt"

    <#
        In PowerShell 5.1 the default behavior is as follows:
            $DebugPreference       = SilentlyContinue
            $InformationPreference = SilentlyContinue
            $ProgressPreference    = Continue
            $VerbosePreference     = SilentlyContinue

        See the following for more information:
        https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-5.1
    #>

    # I am not testing Write-Output as I am not worried about programmatic/pipeline stuff, just contextual messages for end-users or logging

    Write-Host "`nTesting default behavior with transcripts --------------------------------`n"

    # Setting these just in case I launch this script in a session where a previous script might have modified the preference variables
    $DebugPreference = "SilentlyContinue"
    $InformationPreference = "SilentlyContinue"
    $ProgressPreference = "Continue"
    $VerbosePreference = "SilentlyContinue"

    Write-Host "Calling Write-Host"
    Write-Debug "Calling Write-Debug"
    Write-Error "Calling Write-Error" -ErrorAction "Continue"
    Write-Information "Calling Write-Information"
    Write-Progress "Calling Write-Progress"
    Write-Verbose "Calling Write-Verbose"

    Stop-Transcript
    Start-Transcript -Force -Path "$PSScriptRoot\everything_continue.txt"

    Write-Host "`nTesting explicit behavior with transcripts --------------------------------`n"

    # Turn everything on
    $DebugPreference = "Continue"
    $InformationPreference = "Continue" # Setting this to SilentlyContinue makes it show up in the log but not the console. Setting this to 'Continue' makes it show up in the console but not the log.
    $ProgressPreference = "Continue"
    $VerbosePreference = "Continue"

    Write-Host "Calling Write-Host"
    Write-Debug "Calling Write-Debug"
    Write-Error "Calling Write-Error" -ErrorAction "Continue"
    Write-Information "Calling Write-Information"
    Write-Progress "Calling Write-Progress"
    Write-Verbose "Calling Write-Verbose"

    Stop-Transcript

    Write-Host "`nResults -------------------------------------------------------------------`n"

    # See what actually gets captured and written by the transcriber

    $messageTypes = @("Write-Debug", "Write-Error", "Write-Host", "Write-Information", "Write-Verbose")

    Write-Host "Default" -ForegroundColor Cyan
    $lines = Get-Content "$PSScriptRoot\default.txt"
    foreach ($message in $messageTypes) {
        if ($lines -like "*Calling $message*") {
            Write-Host "  $message PRESENT" -ForegroundColor Green
        }
        else {
            Write-Host "  $message MISSING" -ForegroundColor Red
        }
    }

    Write-Host "Everything Continue" -ForegroundColor Cyan
    $lines = Get-Content "$PSScriptRoot\everything_continue.txt"
    foreach ($message in $messageTypes) {
        if ($lines -like "*Calling $message*") {
            Write-Host "  $message PRESENT" -ForegroundColor Green
        }
        else {
            Write-Host "  $message MISSING" -ForegroundColor Red
        }
    }
}
catch {
    Write-Host "----------------------------------------------------------------------------------------------------"
    Write-Host $_.Exception
    Write-Host $_.ScriptStackTrace
    Write-Host "----------------------------------------------------------------------------------------------------"

    try { Stop-Transcript } catch { }

    throw $_
}

1 Ответ

1 голос
/ 16 марта 2019

Вы видите ошибку в Windows PowerShell (с версии 5.1.17134.590), которая исправлена ​​в PowerShell Core (по крайней мере v6.1.0 - хотя другие проблемы, связанные с расшифровкой, сохраняются; см. эту проблему GitHub ).

Я рекомендую вам сообщить об этом на форуме Windows PowerShell UserVoice (обратите внимание, что PowerShell GitHub-repo выпускает форум только для ошибок, присутствующих в PowerShell Core ).

Вот как проверить, присутствует ли ошибка в вашей версии PowerShell:

Создайте скрипт с кодом ниже и запустите его:

'--- Direct output'

$null = Start-Transcript ($tempFile = [io.path]::GetTempFileName())

    # Note that 'SilentlyContinue' is also the default value.
    $InformationPreference = 'SilentlyContinue'

    # Produces no output.
    Write-Information '1-information' 

    # Prints '2-Information' to the console.
    Write-Information '2-information' -InformationAction Continue

$null = Stop-Transcript

'--- Write-Information output transcribed:'

Select-String '-information' $tempFile | Select-Object -ExpandProperty Line

Remove-Item $tempFile

С ошибкой присутствует (Windows PowerShell) вы увидите:

--- Direct output
2-information
--- Write-Information output transcribed:
INFO: 1-information

То есть напротив предполагаемого поведения произошло : в протоколе был записан вызов, которого он не должен иметь (поскольку он не выдал выходных данных), и он не зарегистрировал тот, который должен иметь.

Кроме того, к зарегистрированному выходу добавляется префикс INFO: , что является несоответствием, также исправленным в PowerShell Core.

Не существует полного обходного пути , за исключением того, что выможно использовать Write-Host в случаях, когда do вы хотите, чтобы вывод был записан в стенограмме - но такие вызовы будут регистрироваться безоговорочно независимо от значения переменной предпочтения $InformationPreference (хотя Write-Host формально предоставляет -InformationAction общий параметр, он игнорируется ).


С исправленной ошибкой (PowerShell Core ) вы увидите:

--- Direct output
2-information
--- Write-Information output transcribed:
2-information

Стенограмма теперь соответствует прямому выводу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...