Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

wpf - PowerShell progress Bar invocation fails in Runspace

I am creating a PowerShell script with a GUI, that copies user profiles from a selected source disk to a destination disk. I've created the GUI in XAML, with VS Community 2019.

My copy function is called from a runspace and works fine. I would like to put a progress bar inside this runspace so that it increases for each folder copied, but I can't figure out how.

Here is my runspace :

function RunspaceBackupData {
    $Runspace = [runspacefactory]::CreateRunspace()
    $Runspace.ApartmentState = "STA"
    $Runspace.ThreadOptions = "ReuseThread"
    $Runspace.Open()
    $Runspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
    $Runspace.SessionStateProxy.SetVariable("SelectedFolders",$global:SelectedFolders)
    $Runspace.SessionStateProxy.SetVariable("SelectedUser",$global:SelectedUser)
     $Runspace.SessionStateProxy.SetVariable("ReturnedDiskSource",$global:ReturnedDiskSource)
    $Runspace.SessionStateProxy.SetVariable("ReturnedDiskDestination",$global:ReturnedDiskDestination)
    $code = {
        foreach ($item in $global:SelectedFolders) {
            copy-item -Path "$global:ReturnedDiskSourceUsers$global:SelectedUser$item" -Destination "$global:ReturnedDiskDestinationUsers$global:SelectedUser$item" -Force -Recurse
        }
    }

    $PSinstance = [powershell]::Create().AddScript($Code)
    $PSinstance.Runspace = $Runspace
    $job = $PSinstance.BeginInvoke()
}

Here is my event-handler :

$var_btnStart.Add_Click( {
    RunspaceBackupData -syncHash $syncHash -SelectedFolders $global:SelectedFolders -SelectedUser $global:SelectedUser -ReturnedDiskSource $global:ReturnedDiskSource -ReturnedDiskDestination $global:ReturnedDiskDestination 
})

Can you please help me ?

question from:https://stackoverflow.com/questions/65541355/powershell-progress-bar-invocation-fails-in-runspace

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inside $code you need to keep the count, so I suggest a for-loop.

Inside the loop you can call the dispatcher in the window-object:

$syncHash.Window.Dispatcher.Invoke([action]{$syncHash.Progressbar.Value = [double] <code for finished percentage>}, "Normal") 

I suspect you have window and progressbar in $syncHash


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...