0

I wrote a script which works, but the output is long enough that it would take a large console buffer to capture it all and paste it into a file to save.

I would like to be able to send the result strings both to the screen and to a file.

In the script I used "write-host" liberally, AND these are the strings I want to write to a file. I do not want to use simple redirection so no output goes to the monitor.

I suspect that I need a different approach instead of "write-host", but I have not been able to cobble together anything that works.

Following is a little chunk of the script so you can see basically how I am trying to accomplish the goal of the script. Thank you.

param($FName)
$tgt = Import-Csv $FName
$tgt | ForEach-Object ($_.IPAddr) {
Write-Host Checking IP Address ($_.IPAddr)
Resolve-DnsName -Name $_.IPAddr 2\>$null | Out-Null
$ResolvResult = $?
if ($ResolvResult -eq $TRUE) {
$RevHstName = Resolve-DnsName -name $_.IPAddr | Select-Object  -Property NameHost -First 1
$RevHstName = $RevHstName -replace ".*=" -replace "}"
$TestRoot = ($RevHstName -split ".",3) #\[1\]
if (($TestRoot -like '*-servers\*') -or ($TestRoot -like '*awsdns*'))
{
write-host $_.IPAddr "looks up as a ROOT or AWS SERVER"
}
else
{
write-host "Successful Lookup for" $_.IPAddr "is" $RevHstName
}
.....

I have tried various combinations piping into or out of "Tee-Object", "Write-Output", "Out-File". But I haven't been able to get any of them to work.

  • 1
    Sounds like you're looking for `Tee-Object` – Santiago Squarzon Jun 23 '23 at 21:03
  • 1
    `& { <# your code #> } *>&1 | Tee-Object -FilePath LogFile.txt`. Since PowerShell 5, this merges _all_ output streams into the success streams, so you can pipe them to `Tee-Object`. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-7.3 – zett42 Jun 23 '23 at 21:14
  • Thinking ahead, consider writing yourself a simple ```Write-Log``` cmdlet to centralise all your console / logfile output, then call that instead of ```write-host```. That way if you change how you want your logging to work you only need to edit ```Write-Log``` and not every call site in your code. – mclayton Jun 23 '23 at 22:42
  • @zett42 That worked! I had to change "Write-Host" to "Write-Object", but otherwise, it was a slam dunk. Thanks so much for your help! – Tom Salciccia Jun 27 '23 at 14:53
  • @zett42 Nope. Still "Write-Host". Thank you again. – Tom Salciccia Jun 27 '23 at 19:15

0 Answers0