Bonjour à tous,

Je viens vers vous car je sèche complètement.

J'ai une interface en XAML pour un script powershell.

J'ai une première fenêtre (l'écran principal) où l'on peut rechercher des comptes, et dans celle-ci les comptes s'affichent sur cette même interface.
Ensuite, lorsque l'on sélectionne un ou plusieurs comptes dans cette première fenêtre, une commande powershell se lance pour rechercher les groupes des ces utilisateurs et les résultats s'affichent dans une deuxième fenêtre.

Cette deuxième recherche peut prendre quelques minutes et je souhaiterai que lorsque ce lance la recherche des groupes, une fenêtre intermédiaire s'affiche durant la recherche et se ferme lorsque les résultats s'affichent dans la deuxième fenêtre.

Le problème c'est que ma commande powershell ne se lance pas tant que je n'ai pas quitter manuellement cette fenêtre intermédiaire.

Comment faire pour que ma commande se lance en même temps que interface intermédiaire ? Et que cette interface intermédiaire se ferme à la fin de la recherche ?

Mon code est composé de 3 fichiers :
- un pour le code powershell : Interface.ps1
- un pour la fenêtre principale où l'on lance la recherche des comptes, où les comptes trouvés s'affiche et où l'on peut lancer une recherche sur ces comptes : Interface-Main.xaml
- un pour la 2ème fenêtre qui affiches les résultats des groupes des utilisateurs : Interface-UserDetails.xaml
- un pour la fenêtre intermédiaire pour faire patienter : Interface-WaitingScreen.xaml

Interface-Main.xaml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Gestion des comptes et groupes" Height="492" Width="900">


    <Grid Margin="10">
        <TabControl>
            <!-- Page Comptes -->
            <TabItem Header="Comptes">
                <Grid Margin="10">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <!-- Formulaire Comptes -->
                    <StackPanel Orientation="Vertical" Grid.Row="0" Margin="0 0 0 10">
                        <StackPanel Orientation="Horizontal" Margin="0 0 0 5">
                            <Label Content="UID" Width="100"/>
                            <TextBox Name="txtUserId" Width="200" Margin="0 0 100 0"/>
                            <Label Content="Mail" Width="100"/>
                            <TextBox Name="txtUserEmail" Width="200"/>
                        </StackPanel>
                        <StackPanel Orientation="Horizontal" Margin="0 0 0 5">
                            <Label Content="Nom" Width="100"/>
                            <TextBox Name="txtUserName" Width="200" Margin="0 0 100 0"/>
                            <Label Content="Description" Width="100"/>
                            <TextBox Name="txtUserDescription" Width="200"/>
                        </StackPanel>
                        <StackPanel Orientation="Horizontal" Margin="0 0 0 5">
                            <Label Content="Prénom" Width="100"/>
                            <TextBox Name="txtUserFirstName" Width="200"/>
                        </StackPanel>
                    </StackPanel>

                    <!-- Boutons -->
                    <StackPanel Orientation="Horizontal" Grid.Row="1" Margin="0 0 0 10">
                        <Button Content="Rechercher" Name="btnSearchUser" Width="100" Margin="0 0 10 0"/>
                        <Button Content="RAZ" Name="btnResetUserSearch" Width="100" Margin="0 0 10 0"/>
                        <Button Content="Exporter la liste des comptes" Name="btnExportUserDetail" Width="160" Margin="0 0 10 0"/>
                        <Button Content="Interroger le/les compte(s) sélectionnés" Name="btnQuerySelectedUsers" Width="220" Margin="0 0 10 0" Visibility="Collapsed"/>
                    </StackPanel>
                    
                    <!-- Tableau des résultats -->
                    <DataGrid Name="dataGridUserAccounts" Grid.Row="2" AutoGenerateColumns="True" CanUserAddRows="False" IsReadOnly="True" SelectionMode="Extended">
                    </DataGrid>

                    <!-- Pagination -->
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Grid.Row="3" Margin="0 10 0 0">
                        <Button Content="&lt;" Name="btnPreviousUserPage" Width="30"/>
                        <!-- <TextBlock Text="Page 1 / 1" Margin="10 0"/> -->
                        <Label Content="Page 1 sur 1" Name ="lblUserPageIndicator" VerticalAlignment="Center" Margin="0 0 10 0"/>
                        <Button Content="&gt;" Name="btnNextUserPage" Width="30"/>
                    </StackPanel>
                </Grid>
            </TabItem>
        </TabControl>
    </Grid>
</Window>




Interface-UserDetails.xaml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Export des Groupes du/des Compte(s) sélectionné(s) - $sAMAccountName" Height="600" Width="900">
    <DockPanel Margin="10">
        <Grid DockPanel.Dock="Top">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
                <DataGrid Name="dataGridUserDetails" AutoGenerateColumns="True" DockPanel.Dock="Top" Margin="0,0,0,10"/>
            </ScrollViewer>
            <Button Name="btnExportUserDetails" Content="Exporter la liste" Grid.Row="1" Height="30"/>
        </Grid>
    </DockPanel>
</Window>

Interface-WaitingScreen.xaml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="[TITLE]" Height="100" Width="400" WindowStartupLocation="CenterScreen" ResizeMode="NoResize">
    <DockPanel Margin="10">
        <Grid DockPanel.Dock="Top">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <TextBlock x:Name="TextWaitingScreen"
               Text="Chargement en cours..."
               TextWrapping="Wrap"
               TextAlignment="Center"
               VerticalAlignment="Center"
               HorizontalAlignment="Center"
               FontSize="16"
               FontWeight="Bold"
               Width="360"
               Padding="10"/>
        </Grid>
    </DockPanel>
</Window>

Interface.ps1
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
clear
#region données de test
# ----------- Jeux de données de test ---------------------------------------------------
# Générer 1000 comptes fictifs
$SimulatedUserAccounts = 1..1000 | ForEach-Object {
    [PSCustomObject]@{
        sAMAccountName         = "user_$_"
        sn         = "Nom $_"
        givenName      = "Prenom $_"
        mail        = "prenom$_.nom$_@domaine.com"
        description = "Utilisateur de test $_"
    }
}
#$SimulatedUserAccounts | ogv

# Générer 1000 groupes fictifs
$SimulatedGroups = 1..1000 | ForEach-Object {
    [PSCustomObject]@{
        sAMAccountName         = "Groupe_$_"
        description = "Groupe de test $_"
        displayName = "Ceci est le groupe $_"
        mail        = "groupe$_@domaine.com"
    }
}
#$SimulatedGroups | ogv

# Générer quelques relations fictives Comptes-Groupes
$SimulatedUserGroupRelations = @()
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_1';
    sAMAccountNameG = 'Groupe_1'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_1';
    sAMAccountNameG = 'Groupe_41'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_1';
    sAMAccountNameG = 'Groupe_51'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_2';
    sAMAccountNameG = 'Groupe_2'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_2';
    sAMAccountNameG = 'Groupe_42'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_3';
    sAMAccountNameG = 'Groupe_3'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_3';
    sAMAccountNameG = 'Groupe_43'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_3';
    sAMAccountNameG = 'Groupe_53'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_99';
    sAMAccountNameG = 'Groupe_99'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_100';
    sAMAccountNameG = 'Groupe_100'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_100';
    sAMAccountNameG = 'Groupe_41'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_100';
    sAMAccountNameG = 'Groupe_42'
}
$SimulatedUserGroupRelations += New-Object PSObject -Property @{
    sAMAccountNameU = 'user_100';
    sAMAccountNameG = 'Groupe_43'
}
#$SimulatedUserGroupRelations | ogv
#endregion données de test

#region fonctions
#region fonction DisplayNotification
function DisplayNotification {
    param(
        [string]$Message,
        [string]$Titre = "Information",
        [ValidateSet("Info", "Attention", "Erreur")]
        [string]$Type = "Info"
    )

    # on detecte le mode de lance (ps1 en console ou exe)
    $hasConsole = $true
    try {
        $null = [console]::WindowWidth
    } catch {
        $hasConsole = $false
    }

    if ($hasConsole) {
        # Affichage dans la console classique
        Write-Host - "$Titre : $Message" 
    }
    else {
        switch ($Type) {
            "Info"    { $icone = [System.Windows.MessageBoxImage]::Information }
            "Attention" { $icone = [System.Windows.MessageBoxImage]::Warning }
            "Erreur"   { $icone = [System.Windows.MessageBoxImage]::Error }
        }

        [System.Windows.MessageBox]::Show($Message, $Titre, 'OK', $icone) | Out-Null
    }
}
#region fonction DisplayNotification

#region fonction WaitingScreen
function WaitingScreen {
    param(
        [string]$Message,
        [string]$Titre = "Information"
    )

    # ----------- Charger le XAML - Interface_Export_GroupesCompte ----------------------
    $WaitingScreenXamlFile = Join-Path -Path $Directory -ChildPath 'Interface-WaitingScreen.xaml'
    [xml]$WaitingScreenXamlContent = (Get-Content -Path $WaitingScreenXamlFile).replace("[TITLE]", $($Titre))
    $WaitingScreenXamlReader = New-Object System.Xml.XmlNodeReader $WaitingScreenXamlContent
    $WaitingScreenApplicationWindow = [Windows.Markup.XamlReader]::Load($WaitingScreenXamlReader)

    # On link les objets du XAML
    $TextWaitingScreen = $WaitingScreenApplicationWindow.FindName("TextWaitingScreen")

    $TextWaitingScreen.Text = $Message

    $WaitingScreenApplicationWindow.ShowDialog()  | Out-Null


}
#endregion fonction WaitingScreen

#region fonction FindUserAccount
function FindUserAccount {
    param (
        [string]$uid,
        [string]$nom,
        [string]$prenom,
        [string]$mail,
        [string]$description
    )

    if ($uid -eq "")         { $uid = "*" }
    if ($nom -eq "")         { $nom = "*" }
    if ($prenom -eq "")      { $prenom = "*" }
    if ($mail -eq "")        { $mail = "*" }
    if ($description -eq "") { $description = "*" }

    # Construction du filtre
    $filters = @()

    if ($uid -ne "*") {
        $filters += { (($_.sAMAccountName -like $uid) -or ($_.name -like $uid)) }
    }
    if ($nom -ne "*") {
        $filters += { ($_.sn -like $nom) }
    }
    if ($prenom -ne "*") {
        $filters += { ($_.givenName -like $prenom) }
    }
    if ($mail -ne "*") {
        $filters += { ($_.mail -like $mail) }
    }
    if ($description -ne "*") {
        $filters += { ($_.description -like $description) }
    }

    $finalFilter = $filters -join " -and "
    
    if ($finalFilter -eq "") {
        $finalFilter = "*"
    }
    
    $results = $null
    $results = $SimulatedUserAccounts | Where-Object { $finalFilter }

    return $results
}
#endregion fonction FindUserAccount

#region fonction RetrieveGroupsForUser
function RetrieveGroupsForUser {
    param ([string]$uid)
    
    $Results = New-Object -TypeName 'system.collections.arraylist'
    $groups = $null

    WaitingScreen -Message 'Nous recherchons les groupes de(s) utilisateur(s) sélectionné(s). Merci de patienter le temps que la recherche affiche les resultats.' -Titre 'Recherche en cours des groupes...'

    Sleep -Seconds 5

    #$groups = (Get-ADUser -Identity $uid -Properties memberof).memberof
    $groups = ($SimulatedUserGroupRelations | Where-Object { $_.sAMAccountNameU -eq  $uid}).sAMAccountNameG

    foreach ($group in $groups) {            
        $Results += ($SimulatedGroups | Where-Object { $_.sAMAccountName -eq  $group})
    }
    
    Sleep -Seconds 2

    return $Results
}
#endregion fonction RetrieveGroupsForUser

#region fonction ExportDetailedResults
function ExportDetailedResults {
    param ([array]$donnees, [string]$nomParDefaut = "export.csv")
    $dlg = New-Object System.Windows.Forms.SaveFileDialog
    $dlg.FileName = $nomParDefaut
    $dlg.Filter = "CSV (*.csv)|*.csv"
    if ($dlg.ShowDialog() -eq "OK") {
        $donnees | Export-Csv -Path $dlg.FileName -delimiter ';' -Encoding UTF8 -NoTypeInformation 
        DisplayNotification -Titre "Export des comptes..." -Message "Export effectué : $($dlg.FileName)" -Type 'Info'
    }
}
#endregion fonction ExportDetailedResults

#region RenderPagination
function RenderPagination {
    param (
        [array]$donnees,
        [int]$pageActuelle,
        [int]$taillePage,
        [System.Windows.Controls.DataGrid]$dataGrid,
        [System.Windows.Controls.Label]$labelPagination,
        [int]$totalPages = $null,
        [System.Windows.Controls.Button]$btnPrecedent = $null,
        [System.Windows.Controls.Button]$btnSuivant = $null
    )

    if (-not $donnees -or $donnees.Count -eq 0) {
        $dataGrid.ItemsSource = $null
        $labelPagination.Content = "Page 0 sur 0"
        if ($totalPages) { $totalPages.Value = 0 }
        if ($btnPrecedent) { $btnPrecedent.IsEnabled = $false }
        if ($btnSuivant) { $btnPrecedent.IsEnabled = $false }
        return
    }

    # permet d'éviter des résultats négatif si pageActuelle = 0
    if ($pageActuelle -lt 1) {
        $pageActuelle = 1
    }

    $nbTotalPages = [math]::Ceiling($donnees.Count / $taillePage)
    $indexDebut = ($pageActuelle - 1) * $taillePage    

    $donneesPage = @($donnees | Select-Object -Skip $indexDebut -First $taillePage)

    $dataGrid.ItemsSource = $donneesPage
    $labelPagination.Content = "Page $($PageActuelle) sur $($nbTotalPages)"

    if ($totalPages) {
        $totalPages.Value = $nbTotalPages
    }
}
#endregion RenderPagination

#region RegisterPaginationEvent
function RegisterPaginationEvent {
    param (
        [System.Windows.Controls.Button]$btnPrecedent,
        [System.Windows.Controls.Button]$btnSuivant,
        [array]$GetDonnees,
        [int]$pageActuelle,
        [int]$taillePage,
        [System.Windows.Controls.DataGrid]$dataGrid,
        [System.Windows.Controls.Label]$labelPagination
    )

    $totalPages = 0

    $refresh = {
        RenderPagination -donnees $GetDonnees -pageActuelle $pageActuelle.Value -taillePage $taillePage -dataGrid $dataGrid -labelPagination $labelPagination -totalPages $totalPages -btnPrecedent $btnPrecedent -btnSuivant $btnSuivant 
    }

    $btnPrecedent.Add_Click({
        if ($pageActuelle.Value -gt 1) {
            $pageActuelle.Value--
            & $refresh
        }
    })

    $btnSuivant.Add_Click({
        if ($pageActuelle.Value -lt $totalPages) {
            $pageActuelle.Value++
            & $refresh
        }
    })

    # Premier affichage
    & $refresh
}
#endregion RegisterPaginationEvent
#endregion fonctions


#region MAIN
Add-Type -AssemblyName PresentationFramework

$startupSuccess = $true

# ----------- Répertoire ----------------------------------------------------------------
$Directory = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Definition)

# ----------- Charger le XAML - Interface_Principale ------------------------------------
$PrimaryXamlFile = Join-Path -Path $Directory -ChildPath 'Interface-Main.xaml'
[xml]$PrimaryXamlContent = Get-Content -Path $PrimaryXamlFile
$PrimaryXamlReader = New-Object System.Xml.XmlNodeReader $PrimaryXamlContent
$MainApplicationWindow = [Windows.Markup.XamlReader]::Load($PrimaryXamlReader)

# ----------- COMPTES -------------------------------------------------------------------
# Pagination
$Script:UsersPerPage = 10
$Script:CurrentUserPage = 1
$Script:UserResults = @()

# On link les objets du XAML
$txtUserId             = $MainApplicationWindow.FindName("txtUserId")
$txtUserName           = $MainApplicationWindow.FindName("txtUserName")
$txtUserFirstName      = $MainApplicationWindow.FindName("txtUserFirstName")
$txtUserEmail          = $MainApplicationWindow.FindName("txtUserEmail")
$txtUserDescription    = $MainApplicationWindow.FindName("txtUserDescription")
$dataGridUserAccounts  = $MainApplicationWindow.FindName("dataGridUserAccounts")
$btnSearchUser         = $MainApplicationWindow.FindName("btnSearchUser")
$btnResetUserSearch    = $MainApplicationWindow.FindName("btnResetUserSearch")
$btnExportUserDetail   = $MainApplicationWindow.FindName("btnExportUserDetail")
$btnQuerySelectedUsers = $MainApplicationWindow.FindName("btnQuerySelectedUsers")
$btnPreviousUserPage   = $MainApplicationWindow.FindName("btnPreviousUserPage")
$btnNextUserPage       = $MainApplicationWindow.FindName("btnNextUserPage")
$lblUserPageIndicator  = $MainApplicationWindow.FindName("lblUserPageIndicator")

# Rechercher les Comptes avec les critères renseignés
$btnSearchUser.Add_Click({
    # A chaque recherche on vide les résultats précédents
    $Script:CurrentUserPage = 1
    $dataGridUserAccounts.ItemsSource = $null
    $Script:UserResults = @()
    
    $Script:UserResults = FindUserAccount -uid $txtUserId.Text -nom $txtUserName.Text -prenom $txtUserFirstName.Text -mail $txtUserEmail.Text -description $txtUserDescription.Text
   
    # S'assurer que $resultats est toujours dans le format d'un tableau
    if ($Script:UserResults -isnot [System.Collections.IEnumerable] -or $Script:UserResults -is [string]) {
        $Script:UserResults = @($Script:UserResults)
    }

    # On charge dataGridComptes uniquement si le filtre a retourné au moins un résultat
    if ($Script:UserResults.Count -gt 0) {
        RegisterPaginationEvent -btnPrecedent $btnPreviousUserPage -btnSuivant $btnNextUserPage -GetDonnees $Script:UserResults -pageActuelle $Script:CurrentUserPage -taillePage $Script:UsersPerPage -dataGrid $dataGridUserAccounts -labelPagination $lblUserPageIndicator
    }
    else {
        DisplayNotification -Titre "Comptes" -Message 'Aucun compte ne correspond à vos critères !' -Type 'Info'
    }
})

# Action du bouton Précédent pour la pagination
$btnPreviousUserPage.Add_Click({   
    if ($Script:CurrentUserPage -gt 1) {
        $Script:CurrentUserPage--
        RenderPagination -donnees $Script:UserResults -pageActuelle $Script:CurrentUserPage -taillePage $Script:UsersPerPage -dataGrid $dataGridUserAccounts -labelPagination $lblUserPageIndicator -btnPrecedent $btnPreviousUserPage -btnSuivant $btnNextUserPage 
    }
})

# Action du bouton Suivant pour la pagination
$btnNextUserPage.Add_Click({
    $totalPagesComptes = [math]::Ceiling($Script:UserResults.Count / $Script:UsersPerPage)
    if ($Script:CurrentUserPage -lt $totalPagesComptes) {
        $Script:CurrentUserPage++
        RenderPagination -donnees $Script:UserResults -pageActuelle $Script:CurrentUserPage -taillePage $Script:UsersPerPage -dataGrid $dataGridUserAccounts -labelPagination $lblUserPageIndicator -btnPrecedent $btnPreviousUserPage -btnSuivant $btnNextUserPage 
    }
})

# Effacer les champs de la page Comptes
$btnResetUserSearch.Add_Click({
    # Effacer les champs
    $txtUserId.Text         = ""
    $txtUserName.Text         = ""
    $txtUserFirstName.Text      = ""
    $txtUserEmail.Text        = ""
    $txtUserDescription.Text = ""
    $Script:UserResults = @()
    $dataGridUserAccounts.ItemsSource = $null
    $Script:CurrentUserPage = 1
    $btnQuerySelectedUsers.Visibility = 'Collapsed'
    $lblUserPageIndicator.Content = "Page 0 sur 0"
})

# Export en CSV des comptes
$btnExportUserDetail.Add_Click({
    if ($Script:UserResults.Count -gt 0) {
        $TimeStamp = Get-Date -UFormat '%Y%m%d-%H%M%S'
        ExportDetailedResults -donnees $Script:UserResults -nomParDefaut "$($TimeStamp)_comptes.csv"
    }
})

# Afficher le bouton Export Groupes de Comptes
$dataGridUserAccounts.Add_SelectionChanged({
    if ($dataGridUserAccounts.SelectedItem -ne $null) {
        $btnQuerySelectedUsers.Visibility = 'Visible'
    } else {
        $btnQuerySelectedUsers.Visibility = 'Collapsed'
    }
})

# Afficher la nouvelle fenêtre avec les groupes présents dans les comptes selectionnés
$btnQuerySelectedUsers.Add_Click({
    $comptes = $dataGridUserAccounts.SelectedItems
    
    if ($comptes -eq $null -or $comptes -eq 0 ) { return }

    $boucle = 0
    $groupsLinkedToAccounts = @()
    $uids = $null

    foreach ($compte in $comptes) {
        $uid = $null
        #$compte | ogv
        $uid = $compte.sAMAccountName
        
        if($boucle -eq 0) {
            $uids = $($uid)
            #write-host "uid dans main boucle 0 = $($uid)"
            $groupsLinkedToAccounts = RetrieveGroupsForUser -uid $uid
            $boucle++
        }
        else {
            $uids = "$($uids)-$($uid)"
            #write-host "uid dans main boucle sup 0 = $($uid)"
            $groupsLinkedToAccounts += RetrieveGroupsForUser -uid $uid
        }
    }

    # ----------- Charger le XAML - Interface_Export_GroupesCompte ----------------------
    $UserXamlFile = Join-Path -Path $Directory -ChildPath 'Interface-UserDetails.xaml'
    [xml]$UserXamlContent = (Get-Content -Path $UserXamlFile).replace("`$sAMAccountName", $($uids))
    $UserXamlReader = New-Object System.Xml.XmlNodeReader $UserXamlContent
    $UserApplicationWindow = [Windows.Markup.XamlReader]::Load($UserXamlReader)

    # On link les objets du XAML
    $dataGridUserDetails = $UserApplicationWindow.FindName("dataGridUserDetails")
    $btnExportUserDetails = $UserApplicationWindow.FindName("btnExportUserDetails")

    $dataGridUserDetails.ItemsSource = $groupsLinkedToAccounts

    # Export en CSV des groupes présents dans les comptes selectionnés
    $btnExportUserDetails.Add_Click({
        $TimeStamp = Get-Date -UFormat '%Y%m%d-%H%M%S'
        ExportDetailedResults -donnees $groupsLinkedToAccounts -nomParDefaut "$($TimeStamp)_groupes($($uids)).csv"
    })

    if ($groupsLinkedToAccounts.Count -lt 1) {
        DisplayNotification -Titre "Interrogation du compte" -Message 'Aucun groupe pour cet utilisateur !' -Type 'Info'
        $dataGridUserDetails.ItemsSource = @("Pas de groupe !")
    }
    else # on affiche la nouvelle fenêtre que s'il y a des résultats !
    {
        $UserApplicationWindow.ShowDialog() | Out-Null
    }
})

# on affiche l'écran principal au démarrage
if($startupSuccess) {
    $MainApplicationWindow.ShowDialog()  | Out-Null
}
#endregion MAIN

La fonction qui affiche la fenêtre intermédiare se trouve en ligne 119 (function WaitingScreen) et elle est applée dans la fonction qui est censée durée longtemps en ligne 191 (function RetrieveGroupsForUser).

Pour les tests, on peut sélectionner user_1.

Merci beaucoup pour votre aide, cela fait plusieurs semaines que je sèche.

misterg94