In a PowerShell script I want to make a transcript of whatever the script is doing with Start-Transcript. However, sometimes the script failed, and a transcript is already running. In that case an error is thrown and I can't find a way to avoid that error. What can I do to fail-safe start a transcript?
If the transcript is already running I would like to simply stop it and start a new one.
The error can be reproduced by intentionally start two transcripts. Remember that in real life a previous run of the script has left the transcript open.
The error situation
PS C:\> Start-Transcript c:\test.txt # pretend that this is a transcript which was not stopped properly by a previous script
Transcript started, output file is c:\test.txt
PS C:\> Start-Transcript c:\test.txt
Start-Transcript : Transcription cannot be started.
At line:1 char:1
+ Start-Transcript c:\test.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
Ignoring the with -ErrorAction SilentlyContinue does not work!
PS C:\> Start-Transcript c:\test.txt # pretend that this is a transcript which was not stopped properly by a previous script
Transcript started, output file is c:\test.txt
PS C:\> Start-Transcript c:\test.txt -ErrorAction SilentlyContinue
Start-Transcript : Transcription cannot be started.
At line:1 char:1
+ Start-Transcript c:\test.txt -ErrorAction SilentlyContinue
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
Stopping the transcript before starting it fails if the transcript was not running
PS C:\> Start-Transcript c:\test.txt
Transcript started, output file is c:\test.txt
PS C:\> Stop-Transcript # pretend that this is a transcript which was not stopped properly by a previous script
Transcript stopped, output file is C:\test.txt
PS C:\> Stop-Transcript
Stop-Transcript : An error occurred stopping transcription: The host is not currently transcribing.
At line:1 char:1
+ Stop-Transcript
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Stop-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.StopTranscriptCommand