2013-04-12 120 views
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语句,标准输出和stderror被重定向到日志文件。

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

在PowerShell中是否有与上面的任何等价物?

+0

看看开始抄本cmdlet:get-help start-trascript -full –

+0

你应该做出答案。顺便说一句日志并不完全是PowerShell的强项。检查[this](https://connect.microsoft.com/PowerShell/feedback/details/283088/script-logging-needs-to-be-improved)和[this](https://connect.microsoft.com/ PowerShell/feedback/details/297055/capture-warning-verbose-debug-and-host-output-via-alternate-streams)out。 –

+0

他们抱怨的是在V3中修复的。流水线,错误,警告,详细和调试流可以分别单独重定向到1-5。 – mjolinor

回答

1

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

  • 外部可执行标准输出,stderr的不捕获

这里的示例代码演示此:

$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文件丢失任何文本颜色。

0

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