Powershell перенаправляет все выходные потоки в файл, а ошибки - в консоль - PullRequest
0 голосов
/ 21 апреля 2020

Я хотел бы перенаправить весь вывод в файл (*> file) и только ошибки на консоль (2>), но не могу найти способ сделать это.

Попробовал это, которое дает ошибка:

Write-Error "error" *> all.log 2>

+ Write-Error "error" *> all.log 2>
+                                 ~
Missing file specification after redirection operator.

Я попытался добавить file, поскольку сообщение об ошибке предлагает просто посмотреть, будет ли перенаправление работать в этом случае, но это не так:

Write-Error "error" *> all.log 2> errors.log
# all.log is empty but should contain the error also
# errors.log contains error

Я также попытался объединить потоки без удачи:

Write-Error "error" 2>&1 all.log 2> errors.log

+ Write-Error "error" 2>&1 all.log 2> errors.log
+                                  ~~~~~~~~~~~~~
The error stream for this command is already redirected.

Пробовал некоторые вещи также с tee, но не смог заставить это работать. Кажется, проблема в том, что вы не можете перенаправить поток более одного раза или вывести его в два места? Есть ли способ обойти это или решить это аккуратно?

1 Ответ

0 голосов
/ 22 апреля 2020

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

Если ваша логика c не слишком сложна, что-то вроде этого должно работать:

function Redirect($output)
{
    # If the last operation was a success $? will be true
    if($?)
    {
        $output | Out-File -FilePath "all.log" -Append
    }
    else
    {
        # $Error[0] is the message of the last error which was already displayed on the screen
        $Error[0] | Out-File -FilePath "all.log" -Append
    }
}


Redirect (Get-ChildItem "exists")
Redirect (Get-ChildItem "nonexistent")

Из командной строки вывод выглядит следующим образом:

PS C:\temp> C:\temp\test.ps1
Get-ChildItem: Cannot find path 'C:\temp\nonexistent' because it does not exist.
At C:\temp\test.ps1:15 char:11
+ Redirect (Get-ChildItem "nonexistent")
+           ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\temp\nonexistent:String) [Get-ChildItem], ItemNotF 
   oundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Содержимое all.log:

    Directory: C:\temp\exists


Mode                 LastWriteTime         Length Name                                               
----                 -------------         ------ ----                                               
-a----        2020-04-22   8:44 AM              0 here.txt                                           


Get-ChildItem : Cannot find path 'C:\temp\nonexistent' because it does not exist.
At C:\temp\test.ps1:15 char:11
+ Redirect (Get-ChildItem "nonexistent")
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\temp\nonexistent:String) [Get-ChildItem], ItemNotF 
   oundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
...