Writing errors and output to a text file and Console

前端 未结 4 1897
走了就别回头了
走了就别回头了 2021-02-02 08:48

I am trying to write the entire output (errors included) of an executing script to the console and a file at the same time. I have tried several different options:



        
4条回答
  •  攒了一身酷
    2021-02-02 09:23

    I wasn't satisfied with any answer I was finding, so I mixed a few and came up with this (in PowerShell 3.0+):

    $output = try{your_command *>&1}catch{$_}
    

    With this you can capture all errors and output that are generated by trying to use your_command.

    It catches exceptions when you use a non-existent command:

    PS C:\Users\jdgregson> $output = try{your_command *>&1}catch{$_}
    PS C:\Users\jdgregson> echo $output
    your_command : The term 'your_command' is not recognized as the name of a
    cmdlet, function, script file, or operable program. Check the spelling of the
    name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:15
    + $output = try{your_command 2>&1}catch{$_}
    +               ~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (your_command:String) [], Comman
       dNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    
    PS C:\Users\jdgregson>
    

    It catches exceptions when you pass invalid arguments to an existing command:

    PS C:\Users\jdgregson> $output = try{cat C:\invalid-path.txt *>&1}catch{$_}
    PS C:\Users\jdgregson> echo $output
    cat : Cannot find path 'C:\invalid-path.txt' because it does not exist.
    At line:1 char:15
    + $output = try{cat C:\invalid-path.txt 2>&1}catch{$_}
    +               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (C:\invalid-path.txt:String) [Ge
       t-Content], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo
       ntentCommand
    

    And it catches the output if there was no problem with your command at all:

    PS C:\Users\jdgregson> $output = try{cat C:\valid-path.txt *>&1}catch{$_}
    PS C:\Users\jdgregson> echo $output
    this file is really here
    

    It works for your example too:

    PS C:\Users\jdgregson> $output = try{Test-Error *>&1}catch{$_}
    PS C:\Users\jdgregson> echo $output
    echo
    WARNING: warning
    Test-Error : error
    At line:1 char:15
    + $output = try{Test-Error *>&1}catch{$_}
    +               ~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorExcep
       tion
        + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
       n,Test-Error
    

提交回复
热议问题