Reducing the time to write Ad query output to windows form grid.

Hi Guys ,

I wrote a GUI based tool (windows forms) for querying AD for several things and i’m having some performance issues with one function in particular. It takes a significant time to write the output to the grid. The function itself is quite fast when run outside of the GUI implementation. So i think the delay is in the way i am writing it to the windows form. Does anyone know how i can optimise this? Relevant code below:


Add-Type -assembly System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.Text ='tool'
$form.Width = 600
$form.Height = 400
$form.AutoSize = $true


$ad_grid = New-Object Windows.Forms.DataGridview
$ad_grid.DataBindings.DefaultDataSourceUpdateMode = 0
$ad_grid.Name = "grouplist"
$ad_grid.DataMember = ""
$ad_grid.TabIndex = 1
$ad_grid.Location = New-Object Drawing.Point 300,40
$ad_grid.Size = New-Object Drawing.Point 800,440
$ad_grid.readonly = $true
$ad_grid.AutoSizeColumnsMode = 'AllCells'
$ad_grid.SelectionMode = 'FullRowSelect'
$ad_grid.MultiSelect = $false
$ad_grid.RowHeadersVisible = $false
$ad_grid.allowusertoordercolumns = $true

Button event handler:

$grid = $ad_grid
$query = "*"+$textBox.Text.ToString()+"*"


function search_ad([string]$lastname){
if ($lastname) {
$array_ad = New-Object System.Collections.ArrayList 
$Script:procInfo = @(Get-ADUser -Filter {Surname -like $lastname} | Get-Adobject -properties *| Select-Object @{Name="UUN";Expression={$_.Name}},@{Name="Surname";Expression={$}},@{Name="Display Name";Expression={$_.Displayname}},@{Name="Department";Expression={$_.Department}},@{Name="Title";Expression={$_.Title}},@{Name="Email";Expression={$_.userPrincipalName}} | sort-object -property UUN)
$grid.DataSource = $array_ad
else {
[windows.forms.messagebox]::show('Please enter a value',[Windows.Forms.MessageBoxIcon]::Warning)

I can provide more of the code if needed, but hopefully these are the relevant sections.


Any help is appreciated :slight_smile:

See the following for your edification:


How much faster is it without the sort?

Thanks guys. The sort doesn’t make much difference. I’ll look into the links provided by Postanote. I don’t think see why it takes so long to write though. Is this an issue with windows forms?




the reason it takes so long to write is related to how the gui works behind the scenes.

you don’t have an actual object to populate your grid-view until the query itself finishes.

you would see the exact same thing occur if you were to do this natively in powershell and pipe to out-gridview.

is there any way i can make it significantly faster or would i be better writing the gui in c# ?