PowerShell使用tee-object时如何移除控制台消息颜色

15

有没有办法在使用tee-object时阻止PowerShell删除控制台消息颜色?

当我不使用tee-object运行时,我可以获得像这样的漂亮错误和详细的PowerShell消息颜色:

powershell.exe -noprofile -file $project_root/test_main.ps1

with color

然而,当我使用tee-object(因为我想要将日志记录到控制台和文件中)时,消息颜色未显示在控制台上(我知道文件不会显示它),如下所示:

powershell.exe -noprofile -file $project_root/test_main.ps1 | tee-object -FilePath $log

no color

如果PowerShell只是使用tee-object将输出分到文件和控制台,为什么我会失去控制台格式?

1个回答

5
尝试使用以下方法:
powershell.exe -noprofile -command { $path\test_main.ps1 | tee-object $log }

这是因为这部分代码先被执行:
powershell.exe -noprofile -file $project_root/test_main.ps1 

tee-object命令所看到的是本机EXE文件的输出。据我所知,PowerShell不会输出错误记录或突出显示本机EXE的stderr输出(除非您重定向错误流,例如2>err.log)。


我明白你的意思,但是我无法让那个命令方法起作用。第一个错误是“必须在'/'运算符的右侧提供值表达式。” 我尝试了转义它,但没有成功。然后我尝试将“$path\test_main.ps1 | tee-object $log”变成$command变量,这样我就可以调用powershell.exe -noprofile -command { $command },但是当我调用不存在的脚本时,它甚至不会调用脚本或抛出错误。正如你所看到的Keith,我正在根据你的博客文章“Effective PowerShell Item 14: Capturing All Output from a Script”来捕获和记录所有输出 :) - DetectiveEric
如果您从PowerShell.exe运行该命令,它应该可以工作(至少在我的测试脚本中是这样的)。如果您在除PowerShell之外的其他地方运行它,请使用 ... -command "&{ $path\test_main.ps1 | tee-object $log }" - Keith Hill
关于“捕获脚本的所有输出”问题,我很失望PowerShell 2.0发布时没有解决这个问题。 :-( - Keith Hill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接