Advertisement
joedigital

ps-redirect

May 23rd, 2025
951
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. While Write-Host is primarily designed to display messages directly to the PowerShell console user interface, and historically its output could not be easily redirected to a file, there are ways to achieve the effect of logging messages that you might also display with Write-Host.
  2.  
  3. Here's a breakdown:
  4.  
  5. Direct Redirection of Write-Host (PowerShell 5.1+):
  6.  
  7. In PowerShell 5.1 and newer, Write-Host now writes to the Information Stream (stream number 6). This means its output can be redirected.
  8. PowerShell
  9.  
  10. # PowerShell 5.1+
  11. $logFile = "C:\temp\mylog.txt"
  12. Write-Host "This is a message for the host." *>> $logFile # Redirects information stream
  13. Write-Host "Another host message." 6>> $logFile        # Explicitly redirecting stream 6
  14. However, relying on this for dedicated logging is generally not considered the best practice because Write-Host's primary purpose is still UI display.
  15. Traditional and Recommended Ways to Log Messages (Applicable to All PowerShell Versions):
  16.  
  17. These methods are more robust and idiomatic for logging:
  18.  
  19. Add-Content: This is often the most straightforward cmdlet for appending text to a file.
  20.  
  21. PowerShell
  22.  
  23. $logFile = "C:\temp\mylog.txt"
  24. $message = "This is a log entry at $(Get-Date)."
  25.  
  26. # Display to host (optional)
  27. Write-Host $message -ForegroundColor Yellow
  28.  
  29. # Append to log file
  30. Add-Content -Path $logFile -Value $message
  31. Out-File -Append: Similar to Add-Content, but Out-File can offer more control over formatting if you were piping complex objects (though for simple strings, they are very similar).
  32.  
  33. PowerShell
  34.  
  35. $logFile = "C:\temp\mylog.txt"
  36. $message = "Error: Something went wrong at $(Get-Date)."
  37.  
  38. Write-Host $message -ForegroundColor Red
  39. $message | Out-File -FilePath $logFile -Append
  40. Write-Output and Redirection: Write-Output writes to the success stream (pipeline), which can be easily redirected. This is the standard way to produce output that other cmdlets can use or that can be sent to a file.
  41.  
  42. PowerShell
  43.  
  44. $logFile = "C:\temp\mylog.txt"
  45. $message = "Processing item X at $(Get-Date)."
  46.  
  47. Write-Host $message # If you still want to see it immediately on the host
  48. Write-Output $message >> $logFile
  49. Tee-Object -Append: If you want to display the message on the host AND write it to a file simultaneously without calling two separate commands for the message itself.
  50.  
  51. PowerShell
  52.  
  53. $logFile = "C:\temp\mylog.txt"
  54. $message = "Important status update at $(Get-Date)."
  55.  
  56. $message | Tee-Object -FilePath $logFile -Append | Write-Host -ForegroundColor Cyan
  57. # Note: Write-Host here is just to show it on screen with color.
  58. # If you just did: $message | Tee-Object -FilePath $logFile -Append
  59. # it would go to the host (as pipeline output) and the file.
  60. Custom Logging Function: This is a very common and recommended practice for more structured logging.
  61.  
  62. PowerShell
  63.  
  64. function Write-Log {
  65.     param(
  66.         [Parameter(Mandatory=$true)]
  67.         [string]$Message,
  68.  
  69.         [string]$LogPath = "C:\temp\mylog.txt",
  70.  
  71.         [switch]$NoHostDisplay
  72.     )
  73.  
  74.     $timestampedMessage = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $Message"
  75.  
  76.     # Append to log file
  77.     try {
  78.         Add-Content -Path $LogPath -Value $timestampedMessage -ErrorAction Stop
  79.     }
  80.     catch {
  81.         Write-Warning "Failed to write to log file $LogPath. Error: $($_.Exception.Message)"
  82.     }
  83.  
  84.  
  85.     # Display to host unless suppressed
  86.     if (-not $NoHostDisplay) {
  87.         Write-Host $timestampedMessage
  88.     }
  89. }
  90.  
  91. # Usage:
  92. Write-Log -Message "Application started."
  93. Write-Log -Message "A warning occurred." -LogPath "C:\temp\anotherlog.txt"
  94. Write-Log -Message "This message only goes to the log." -NoHostDisplay
  95. Start-Transcript and Stop-Transcript: These cmdlets capture everything that appears in the PowerShell console (including Write-Host output, command input, and other stream outputs) to a text file. This is useful for auditing or debugging an entire session.
  96.  
  97. PowerShell
  98.  
  99. Start-Transcript -Path "C:\temp\session_transcript.txt" -Append
  100. # ... your script commands ...
  101. Write-Host "This will be in the transcript."
  102. Get-Process
  103. # ... more commands ...
  104. Stop-Transcript
  105. Recommendation:
  106.  
  107. For general logging, use Add-Content, Out-File -Append, or Write-Output with redirection. Creating a custom Write-Log function is highly recommended for scripts of any significant size as it provides consistency, timestamps, and centralized control over your logging behavior.
  108.  
  109. While you can redirect Write-Host in modern PowerShell, it's often clearer to use cmdlets explicitly designed for file output when logging is your primary goal for that specific piece of information.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement