Josh Petitt
Josh Petitt

Reputation: 9589

How to get progress information resulting from Write-Progress?

I have a PowerShell function that calls Write-Progress. In another function, I would like to get the state of the displayed progress. Is it possible to query the state of the displayed progress?

The use case is this:

I have tagged this as because that is what my environment is.

I have tried looking in the $host variable, as well as the $host.UI and $host.UI.RawUI and could not find what I want.

So for anyone else that is interested, I ended up defining these two functions in a module (kudos for HAL9256 for the inspiration):

function Get-Progress {
    [cmdletbinding()]
    param()

    if (-not $global:Progress) {
        $global:Progress = New-Object PSObject -Property @{
            'Activity' = $null
            'Status' = $null
            'Id' = $null
            'Completed' = $null
            'CurrentOperation' = $null
            'ParentID' = $null
            'PercentComplete' = $null
            'SecondsRemaining' = $null
            'SourceId' = $null
        }
    }

    $global:Progress
}




function Show-Progress {
    [cmdletbinding()]
    param()

    $progress = $global:Progress

    $properties = $progress.PSObject.Properties | Where {$_.MemberType -eq 'NoteProperty'}

    $parameters = @{}
    foreach ($property in $properties) {
        if ($property.Value) {
            $parameters[$property.Name] = $property.Value
        }
    }

    if ($parameters.Count) {
        Write-Progress @parameters
    }
}

Upvotes: 2

Views: 901

Answers (2)

HAL9256
HAL9256

Reputation: 13523

I have experienced a similar issue, where I have a module that runs the script operations and a separate Logging module that has to log progress. The easiest, and from all the possible methods is most reliable method (and I know people will shudder) is to use a global variable.

If you don't want to have a bunch of extra parameters passed back and forth, this is the best method.

#Set global variable
$global:Progress = 10

#------ Other function -----------

#Write Progress
Write-Progress -Activity 'foo' -PercentComplete $global:Progress

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

There's nothing to query. You must keep track of/calculate the percentage yourself and pass it to the cmdlet, otherwise Write-Progress wouldn't know what to display.

Give function B an additional parameter and add a counter to function A:

function A {
  $i = 1
  1..10 | % {
    B (10 * $i)
    $i++
  }
}

function B($p) {
  Write-Progress -Activity 'foo' -PercentComplete $p
}

Upvotes: 1

Related Questions