我正在将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中有没有与上面类似的东西?
发布于 2013-04-14 03:26:53
PowerShell 2,3,x具有尝试将PowerShell窗口的所有输出记录到文本文件的Transcript cmdlets。这里有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文件中的所有文本颜色。
发布于 2013-04-15 09:22:58
如果我真的需要有选择地重定向整个脚本的输出流,我会将其作为后台作业运行。子作业的每个作业流都在一个单独的缓冲区中,可以从作业对象中读取,因此您几乎可以对它们做任何想做的事情,包括在作业运行时读取它们。
https://stackoverflow.com/questions/15979060
复制相似问题