Share via


Write-Progress & WPK

A nifty trick that you can do in WPK is create a WPF progress bar to show the Write-Progress output from a PowerShell script.  I was reminded that people actually wanted to do this when I ran across a question on StackOverflow, and posted this answer.

In case you don’t want to follow the link, here’s a quick script to show progress from a background runspace in WPK.  The top half set ups a bunch of data bindings that will bind to whatever DataContext is found, and the second half of the script is a small sample of Write-Progress output.

 New-Grid -Columns 2 {            
    New-TextBlock -Margin 10 -TextWrapping Wrap -ZIndex 1 -HorizontalAlignment Left -FontWeight Bold -FontSize 12 -DataBinding @{            
        "Text" = "LastProgress.Activity"            
    }            
    New-TextBlock -Margin 10 -ZIndex 1 -TextWrapping Wrap -Column 1 -VerticalAlignment Bottom -HorizontalAlignment Right -FontStyle Italic -FontSize 12 -DataBinding @{            
        "Text" = "LastProgress.StatusDescription"            
    }            
    New-ProgressBar -ColumnSpan 2 -MinHeight 250 -Name ProgressPercent -DataBinding @{            
        "Value" = "LastProgress.PercentComplete"            
    }            
} -DataContext {            
    Get-PowerShellDataSource -Script {             
        foreach ($n in 1..100) {            
            Write-Progress "MajorProgress" "MinorProgress" -PercentComplete $n            
            Start-Sleep -Milliseconds 250            
        }            
    }            
} -AsJob            

Hope this Helps

James Brundage [MSFT]

Comments

  • Anonymous
    July 24, 2011
    In this example the datacontext is bound directly to that script. How can I bind this progress bar to a script of one of the buttons of the xaml ?       New-Button -Name "cmdOK" -Content "_OK" -Row 1 -Column 1 -Margin 5 -Width 115 -HorizontalAlignment Right -VerticalAlignment Bottom  -On_Click { $cmdOK = $window | Get-ChildControl cmdOK if ( $cmdOK.Content -eq "End" ) { $cmdOK.IsCancel = $true } else { $lblRed = $window | Get-ChildControl lblRed #$lblWorkInProgress.Content = "Work In Progress !" #$lblWorkInProgress.Background = $lblRed.Background $window.Height = 300 $cmdOK.Content = "Work In Progress" Do-ProcessInput $window $lblWorkInProgress.Content = "Finished" $lblWorkInProgress.Background = $window.Background $cmdOK.Content = "End" } I have a couple of write-progress statements in this Do-ProcessInput  routine.