3

我正在将 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中是否有与上述内容等效的内容?

4

2 回答 2

1

PowerShell 2,3,x 具有尝试将 PowerShell 窗口的所有输出记录到文本文件的Transcript cmdlet 。一些限制

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

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

$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

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

有一些解决方法:

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

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

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

& hostname.exe | Out-Default

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

于 2013-04-13T19:26:52.943 回答
0

如果我真的需要选择性地重定向整个脚本的输出流,我会将它作为后台作业运行。子作业的每个作业流都在一个单独的缓冲区中,可以从作业对象中读取,因此您几乎可以对它们做任何您想做的事情,包括在作业运行时读取它们。

于 2013-04-15T01:22:57.993 回答