Test if a transcript is running

PowerShell has the ability to create a transcript of the commands you run at the console and the results displayed in the console. But how can you test if a transcript is running?

It used to be that you could only have a single transcript running but Windows PowerShell v5.1 and PowerShell v6.x and later allow multiple transcripts to be running in the same session.

Only way I can think of testing if transcript has been started is to use

Get-History | where CommandLine -like ‘Start-Transcript*’

that doesn’t tell if its still running for which you need

Get-History | where CommandLine -like ‘Stop-Transcript*’

PS> (Get-History | where CommandLine -like ‘Start-Transcript*’).Count –  (Get-History | where CommandLine -like ‘Stop-Transcript*’).Count

should give a result of zero if no transcripts are running. A positive result indicates transcripts are running. A negative result indicates problems.

The test can be wrapped in a function

function test-runningtranscript {
     $starts = (Get-History | Where-Object CommandLine -like ‘Start-Transcript*’).Count
     $stops =  (Get-History | Where-Object CommandLine -like ‘Stop-Transcript*’).Count

    $trans = $starts – $stops

    switch ($trans){
         0           {$false}
         {$_ -gt 0}  {$true}
         {$_ -lt 0}  {Throw “Error!!!  Can’t have negative transcripts”}

You’ll get True return if there is a transcript running and False if there isn’t.

This entry was posted in Powershell. Bookmark the permalink.

3 Responses to Test if a transcript is running

  1. th3l0nius says:

    Here is a working one:

    function test-RunningTranscript {
    $tcount = 0
    Get-History |
    ? CommandLine -Match ‘(Start|Stop)-Transcript’ |
    % {
    if ($_.CommandLine -match ‘Start-Transcript’){ $tcount++ }
    else { $tcount– }
    $tcount = [math]::Max($tcount, 0)
    $tcount -gt 0

    By the way: I never use aliases in scripts except for % and ?.

  2. Oliv says:

    Hi Richard
    Ed wilson wrote and it’s not the only one (https://devblogs.microsoft.com/scripting/using-powershell-aliases-best-practices/).

    In addition, the PSScriptAnalyzer module doesn’t like aliases in scripts and functions (this and trailling spaces are the 2 most common causes for me).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s