3

I'm very new to powershell and I'm looking to pipe all lines to an output file for logging with it's time, but I would rather not explicitly pipe all cmdlets to the log file to avoid visual clutter and to make the code easily extensible.

I'm not sure whether existing methods do what I'm asking and I just can't recognize it or what but any pointers or help would be appreciated.

comp.sci.intern
  • 75
  • 1
  • 1
  • 6

1 Answers1

3

If you want to capture all of the output generated in a PowerShell session (including other streams such as verbose or error messages) you can use Start-Transcript at the start of your script and Stop-Transcript at the end.

If you want to output specific log entries, consider using a Write-Log function as described in one of the answers here: Create Log File in Powershell

Or here's a simple version to get your started:

function Write-Log {
    Param(
        $Message,
        $Path = "$env:USERPROFILE\log.txt"
    )

    function TS {Get-Date -Format 'hh:mm:ss'}
    "[$(TS)]$Message" | Tee-Object -FilePath $Path -Append | Write-Verbose
}

Write-Log 'Some message'

This adds a timestamp to the start of the message and directs it to the Verbose output stream as well as a file via Tee-Object. You can then see the Verbose messages if you enable them via $VerbosePreference (or by supporting -Verbose in your script).

Alternatively, if you want to redirect all output from your script that isn't the other message streams (e.g just things sent to the standard pipeline) you could save the script, run it from within PowerShell and then pipe its output to another command such as Out-File, e.g:

.\yourscript.ps1 | Out-File output.txt
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • Thanks. Is there a well known way to achieve the write-log behavior for every line of code that would otherwise go into the pipeline without passing every line to a function? – comp.sci.intern Jul 25 '17 at 18:02
  • I guess you could save it as a script and then execute it from the shell and send its output to out-file – Mark Wragg Jul 25 '17 at 18:11