powershelltranscriptioninteractive-transcript

Start-Transcript not honouring the $Transcript variable


I have this code at the start of a long script that runs overnight unattended:

$Path       = "E:\Scripts\Weekly_Stats\Output\Version6-4\Transcripts"
$datetime   = Get-Date -F 'yyyyMMddHHmmss'
$filename   = "Transcript-ComputersUsersAdminsSMB-${datetime}.txt"
$Transcript = (Join-Path -Path $Path -ChildPath $filename).ToString()
Start-Transcript

$Transcipt is set to use a path on a drive everyone in the team has access to, but the script fails to honour that variable and puts the transcript file in the My Documents folder of the logged on user.

This example code from MS Learn for Start-Transcript forms the basis of my attempt

$sharePath  = '\\Server01\Transcripts'
$username   = $Env:USERNAME
$hostname   = hostname
$version    = $PSVersionTable.PSVersion.ToString()
$datetime   = Get-Date -F 'yyyyMMddHHmmss'
$filename   = "Transcript-${username}-${hostname}-${version}-${datetime}.txt"
$Transcript = (Join-Path -Path $sharePath -ChildPath $filename).ToString()
Start-Transcript

I have renamed the appropriate fields, removed those I felt unnecessary in my requirements and tried to make the join work so I can save files locally. If I check the value held by $Transcript, it appears to be what I require.

$Transcript is listed as a Preference variable here. The MS Learn Article cited for the sample code does use it this way.

How do I get this to honour the path in $Transcript?


Solution

  • You have done nothing wrong here.
    The example you used as source is meant to be run directly in the console, not in a script (and it would be better if it mentioned that).
    The issue is this:

    I have this code at the start of a long script

    When you check the actual description of the $Transcript variable, you'll find the following:

    $Transcript
    [...] If you don't specify a value for the Path parameter, Start-Transcript uses the path in the value of the $Transcript global variable. [...]

    The $Transcript variable in your script is (by default) defined in the Script scope, not the Global scope, so Start-Transcript won't use it and fall back to the default path.

    Defining $Transcript as global variable will work:

    $Global:Transcript = (Join-Path -Path $Path -ChildPath $filename).ToString()
    

    You should also then always include the scope if you're using it later in the script.

    Or, as @iron suggested, just use the Path or LiteralPath parameters.