Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell equivalent to bash `exec > >(tee -a $logfile); exec 2> >(tee -a $logfile >&2)`

I am porting bash script logging to Powershell, which has the following at the top of the file:

# 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

With the exec statements, both stdout and stderror are redirected to the logfile.

The exec command in bash is really nice as redirection is setup once at the start of the script. I want to avoid explicitly setting up redirection on each command if possible.

Is there any equivalent to the above in PowerShell?

like image 465
morleyc Avatar asked Jan 29 '26 20:01

morleyc


1 Answers

PowerShell 2,3,x have the Transcript cmdlets that attempt to record all output of the PowerShell window to a text file. There are some limitations.

  • external executable stdout, stderr are not captured

Here's example code which demonstrates this:

$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

Everything above will be captured in script_log.txt except for the output of hostname.exe since it is an external executable.

There are some work arounds:

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

This captures everything including hostname.exe's output but it is something done outside of the script.

Another is for each external command, pipe output through the host API:

& hostname.exe | Out-Default

This is done in the script, but you lose any text coloring from the exe on the shell window.

like image 110
Andy Arismendi Avatar answered Feb 01 '26 10:02

Andy Arismendi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!