gpt4 book ai didi

shell - PowerShell 相当于 bash `exec >>(tee -a $logfile); exec 2>>(tee -a $logfile >&2)`

转载 作者:行者123 更新时间:2023-12-04 22:52:48 27 4
gpt4 key购买 nike

我正在将 bash 脚本日志记录移植到 Powershell,它在文件顶部有以下内容:

# redirect stderr and stdout
backupdir="/backup"
logfile=$backupdir/"std.log"
exec > >(tee -a $logfile)
exec 2> >(tee -a $logfile >&2)
echo "directory listing:"
ls -la

通过 exec 语句,stdout 和 stderror 都被重定向到日志文件。

bash 中的 exec 命令非常好,因为在脚本开始时设置一次重定向。如果可能,我想避免在每个命令上显式设置重定向。

在 PowerShell 中是否有与上述等效的东西?

最佳答案

PowerShell 2,3,x 有 Transcript cmdlets尝试将 PowerShell 窗口的所有输出记录到文本文件中。有some limitations .

  • 不捕获外部可执行标准输出、标准错误

下面是演示这一点的示例代码:

$this_path = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
$log_path = Join-Path -Path $this_path -ChildPath script_log.txt
Start-Transcript -Path $log_path
$VerbosePreference = "continue"
$ErrorActionPreference = "continue"
$DebugPreference = "continue"
$WarningPreference = "continue"
& hostname.exe
Write-Host "write-host"
Write-Verbose "write-verbose"
Write-Error "write-error"
Write-Debug "write-debug"
Write-Warning "write-warning"
Get-Date
Stop-Transcript
& notepad $log_path

除了 hostname.exe 的输出外,上面的所有内容都将被捕获到 script_log.txt 中,因为它是一个外部可执行文件。

有一些解决方法:

powershell.exe -noprofile -file script.ps1 > script.log

这会捕获所有内容,包括 hostname.exe 的输出,但它是在脚本之外完成的。

另一个是针对每个外部命令,通过主机 API 管道输出:

& hostname.exe | Out-Default

这是在脚本中完成的,但是您会丢失 shell 窗口中 exe 的任何文本着色。

关于shell - PowerShell 相当于 bash `exec >>(tee -a $logfile); exec 2>>(tee -a $logfile >&2)`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15979060/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com