How to make a Progressbar run while a command is running

Hi guys,

I have a form with a Powershell script behind, which is searching the Active Directory for printer queues. So, when I hit the “Scan” button, it starts searching the AD and will then display the results in a datagridview.
My problem is that this scan might take some 10-15 seconds, maybe even more, depending on the connection speed.
Therefore I added a ProgressbarOverlay and set the “Visible” property to $false and the “Style” to Marquee.
What I want to achieve: when I press “Scan”, the ProgressbarOverlay should appear and run until the command has finished. Then disappear again.
This is what I tried so far:
$buttonScan_click={
$progressbaroverlay1.visible = $true
Get-ADObject -filter {objectclass -eq “printQueue”} -Searchbase $Searchbase -Properties serverName,printerName,Location,Description,driverName | foreach-object {$datagridview1.Rows.Add($.serverName,$.printerName,$.Location,$.Description,$_.driverName)}
$progressbaroverlay1.visible = $false
}

In this case, the progressbaroverlay does not even appear (because the $true and $false commands are executed both at the end or something like that).
When I delete the last row, which is setting “Visible” to $false, then the progressbar appears, but only after the scan has finished and the datagridview has been populated. But it’s too late. I need it to appear before the Get-ADObject command and disappear afterwards.
Does anyone have any ideas?

PS: I also tried the same by replacing $progressbaroverlay1.visible=$true with adding a label and setting $label1.text = “Searching…”. I get the same behaviour, the label changes only at the end, after the datagridview was populated.

I figured it out!
It was because the form wasn’t refreshing, so I had to do it like this:

$buttonScan_click={
$progressbaroverlay1.visible = $true
$MainForm.Refresh()
Get-ADObject -filter {objectclass -eq “printQueue”} -Searchbase $Searchbase -Properties serverName,printerName,Location,Description,driverName | foreach-object {$datagridview1.Rows.Add($.serverName,$.printerName,$.Location,$.Description,$_.driverName) | Foreach-Object {$MainForm.Refresh()}}
$progressbaroverlay1.visible = $false
}

But take care! The Refresh for each object will slow down the search a lot!! Instead of taking 5 seconds to search, it took me about 30-40 seconds.