Hello,

Je souhaite implémenter une console powershell dans un windows form, après avoir fait des recherches (essentiellement avec Chat GPT), je n'arrive pas à rendre ce projet exploitable,

Chat GPT m'a suggéré de faire un RichTextBox, un TextBox et un bouton pour gérer l'entrée et la sortie,

Remarque : Ce projet consiste a créer un Front pour des utilisateurs lambda, ces utilisateurs vont se connecter en SSH à un serveur Linux dans lequel ils devront faire des commandes,

Mon problème : Lorsque je fait une commande si le retour comporte trop de caractère ça plante, je pense qu'il faut allouer plus de ressource mais je sèche, Chat GPT m'a proposé divers solutions mais toujours pareil ça plante, au moment de se connecter en SSH le serveur fait un retour avec un nombre !très! important de caractère (au moins 100 voir plus).

Contrainte : J'utilise Powershell pour ce projet car je souhaite faire un front dans un environnement restreint (dans lequel je ne suis pas autorisé à installer une application ou quelconque package donc utiliser uniquement les outils trouvable sur windows comme batch, powershell etc)

Mon code (il s'agit d'une version de test, mon code source est totalement différent, lorsque ce code "test" sera fonctionnel je l'implémenterai dans mon code source) :

Je suis pas encore à l'aise avec Powershell (Je vous demande d'être indulgeant)

Merci encore pour vos retour,

Cdt,

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

<# ################ Début du Script ################ #>

# Appeler Windows Forms
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
Add-Type -AssemblyName System.Drawing

# Fonction pour centrer dynamiquement les contrôles
function Center-Control {
    param (
        [System.Windows.Forms.Control]$Control,
        [System.Windows.Forms.Form]$Form,
        [int]$OffsetY = 0 # Décalage vertical optionnel
    )
    $formWidth = $Form.ClientSize.Width
    $controlWidth = $Control.Width
    $Control.Location = New-Object System.Drawing.Point(
        ([int]($formWidth - $controlWidth) / 2), 
        $OffsetY
    )
}

# Création du formulaire principal
$API = New-Object System.Windows.Forms.Form
$API.StartPosition = "CenterScreen"
$API.ClientSize = New-Object System.Drawing.Size(1024, 768)
$API.Text = "API"

$API.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$API.MaximizeBox = $false
$API.MinimizeBox = $true


<# ------------------ Création onglet API ------------------ #>

# Ajouter le contrôle TabControl
$tabControl_API = New-Object System.Windows.Forms.TabControl
$tabControl_API.Dock = [System.Windows.Forms.DockStyle]::Fill
$API.Controls.Add($tabControl_API)

# Ajouter un onglet pour l'application complète
$tab_API = New-Object System.Windows.Forms.TabPage
$tab_API.Text = "API Teraterm"
$tabControl_API.TabPages.Add($tab_API)

<# ------------------ Création des objets ------------------ #>

# Fonction pour centrer un tableau de GroupBox
function Center-GroupBoxes {
    param (
        [System.Windows.Forms.Form]$Form,
        [System.Collections.ArrayList]$GroupBoxes,
        [int]$OffsetY = 0 # Décalage vertical pour positionner les GroupBox
    )
    $formWidth = $Form.ClientSize.Width
    $totalWidth = 0
    $spacing = 20 # Espacement horizontal entre les GroupBox

    # Calculer la largeur totale des GroupBox avec espace
    foreach ($groupBox in $GroupBoxes) {
        $totalWidth += $groupBox.Width + $spacing
    }
    $totalWidth -= $spacing # Retirer l'espace supplémentaire après la dernière GroupBox

    # Position initiale pour centrer toutes les GroupBox
    $currentX = ([int]($formWidth - $totalWidth) / 2)

    # Positionner chaque GroupBox
    foreach ($groupBox in $GroupBoxes) {
        $groupBox.Location = New-Object System.Drawing.Point($currentX, $OffsetY)
        $currentX += $groupBox.Width + $spacing
    }
}

# Fonction pour centrer un tableau de boutons
function Center-Buttons {
    param (
        [System.Windows.Forms.Form]$Form,
        [System.Collections.ArrayList]$Buttons,
        [int]$OffsetY = 0 # Décalage vertical pour positionner les boutons
    )
    $formWidth = $Form.ClientSize.Width
    $currentY = $OffsetY # Position verticale initiale

    # Espacement vertical entre les boutons
    $buttonSpacing = 10

    # Positionner chaque bouton sur une nouvelle ligne
    foreach ($button in $Buttons) {
        # Centrer le bouton horizontalement et positionner sur une nouvelle ligne
        $button.Location = New-Object System.Drawing.Point(
            ([int]($formWidth - $button.Width) / 2), 
            $currentY
        )
        $currentY += $button.Height + $buttonSpacing # Décalage vertical pour le prochain bouton
    }
}

# Créer un group box avec des contrôles associés
function Create-GroupBox {
    param (
        [string]$Title,
        [array]$ButtonTexts,  # Liste de texte pour les boutons
        [int]$BoxWidth = 180, # Largeur par défaut
        [int]$BoxHeight = 220, # Hauteur par défaut
        [int]$ButtonWidth = 125, # Largeur du bouton par défaut
        [array]$ButtonActions  # Liste des actions pour chaque bouton
    )

    $GroupBox = New-Object System.Windows.Forms.GroupBox
    $GroupBox.Size = New-Object System.Drawing.Size($BoxWidth, $BoxHeight)
    $GroupBox.Text = $Title

    # Calculer l'espace entre les boutons
    $buttonSpacing = 10
    $currentY = 30  # Position verticale initiale

    for ($i = 0; $i -lt $ButtonTexts.Length; $i++) {
        $Button = New-Object System.Windows.Forms.Button
        $Button.Text = $ButtonTexts[$i]
        $Button.Size = New-Object System.Drawing.Size($ButtonWidth, 35)  # Augmenter la hauteur des boutons
        $Button.Location = New-Object System.Drawing.Point(([int]($BoxWidth - $ButtonWidth) / 2), $currentY)
        $Button.BackColor = [System.Drawing.Color]::LightBlue
        $Button.ForeColor = [System.Drawing.Color]::DarkBlue
        $Button.Add_Click($ButtonActions[$i])

        $GroupBox.Controls.Add($Button)

        # Déplacer la position pour le bouton suivant
        $currentY += $Button.Size.Height + $buttonSpacing
    }

    return $GroupBox
}

# Fonction pour créer un RichTextBox
function Create-RichTextBox {
    param (
        [string]$Text,         # Titre à afficher dans le RichTextBox
        [int]$X = 10,           # Position X
        [int]$Y = 10,            # Position Y
        [int]$richTextBoxWidth = 100, #Taille de la RichTextBox
        [int]$richTextBoxHeight = 100 #Taille de la RichTextBox
    )

    $richTextBox = New-Object System.Windows.Forms.RichTextBox
    $richTextBox.Size = New-Object System.Drawing.Size($richTextBoxWidth, $richTextBoxHeight)
    $richTextBox.Location = New-Object System.Drawing.Point($X, $Y)
    $richTextBox.Font = New-Object System.Drawing.Font("Consolas", 10)
    $richTextBox.BackColor = [System.Drawing.Color]::Black
    $richTextBox.ForeColor = [System.Drawing.Color]::White
    $richTextBox.ReadOnly = $true
    $richTextBox.Text = $Text

    return $richTextBox
}

# Fonction pour créer un TextBox
function Create-TextBox {
    param (
        [int]$TextBoxPosX = 10,           # Position X
        [int]$TextBoxPosY = 10,            # Position Y
        [int]$TextBoxWidth = 100, #Taille de la RichTextBox
        [int]$TextBoxHeight = 100 #Taille de la RichTextBox
    )

    $TextBox = New-Object System.Windows.Forms.RichTextBox
    $TextBox.Size = New-Object System.Drawing.Size($TextBoxWidth, $TextBoxHeight)
    $TextBox.Location = New-Object System.Drawing.Point($TextBoxPosX, $TextBoxPosY)

    return $TextBox
}

# Fonction pour créer un ExecButton
function Create-ExecButton {
    param (
        [int]$ExecButtonPosX = 10,            # Position X
        [int]$ExecButtonPosY = 10,            # Position Y
        [int]$ExecButtonWidth = 100,          #Taille du TextBox
        [int]$ExecButtonHeight = 100          #Taille du TextBox
    )

    $ExecButton = New-Object System.Windows.Forms.Button
    $ExecButton.Size = New-Object System.Drawing.Size($ExecButtonWidth, $ExecButtonHeight)
    $ExecButton.Location = New-Object System.Drawing.Point($ExecButtonPosX, $ExecButtonPosY)
    $ExecButton.Text = "Envoyer"

    return $ExecButton
}

# Fonction pour créer un CloseButton
function Create-CloseButton {
    param (
        [int]$CloseButtonPosX = 985,         # Position X
        [int]$CloseButtonPosY = 5,           # Position Y
        [int]$CloseButtonWidth = 30,         #Taille du Bouton
        [int]$CloseButtonHeight = 30         #Taille du Bouton
    )

    $CloseButton = New-Object System.Windows.Forms.Button
    $CloseButton.Text = "X"
    $CloseButton.Size = New-Object System.Drawing.Size($CloseButtonWidth, $CloseButtonHeight)
    $CloseButton.Location = New-Object System.Drawing.Point($CloseButtonPosX, $CloseButtonPosY)
    $CloseButton.BackColor = [System.Drawing.Color]::LightCoral
    $CloseButton.ForeColor = [System.Drawing.Color]::White

    return $CloseButton
}

<# ------------------ Utilisation des objets ------------------ #>

# Création des GroupBox dynamiquement
$GroupBoxes = @() # Liste pour stocker les GroupBox

# Définir les boutons pour le premier groupBox
$ButtonTexts1 = @("CPE JUMP")
# Modification de l'action du bouton "CPE JUMP"
$ButtonActions1 = @(
    { 
        # Incrémentation de l'index des onglets pour chaque bouton "CPE JUMP"
        $tabIndex = 1
        $tabExists = $true
        $tabName = "CPE_JUMP_$tabIndex"
        while ($tabExists) {
            $tabExists = $false
            foreach ($tab in $tabControl_API.TabPages) {
                if ($tab.Text -eq $tabName) {
                    $tabExists = $true
                    $tabIndex++
                    $tabName = "CPE_JUMP_$tabIndex"
                    break
                }
            }
        }

# Créer un nouvel onglet
$newTab = New-Object System.Windows.Forms.TabPage
$newTab.Text = $tabName

# Créer un RichTextBox
$global:richTextBox = Create-RichTextBox -Text "PS > " -richTextBoxWidth 985 -richTextBoxHeight 550

# Créer un TextBox
$global:textBox = Create-TextBox -TextBoxWidth 700 -TextBoxHeight 130 -TextBoxPosX 10 -TextBoxPosY 580

# Création du bouton pour exécuter la commande
$global:executeButton = Create-ExecButton -ExecButtonWidth 200 -ExecButtonHeight 100 -ExecButtonPosX 760 -ExecButtonPosY 600

# Ajouter un gestionnaire d'événements pour le bouton "Envoyer"
$global:executeButton.Add_Click({
    # Ajouter le texte du TextBox au RichTextBox sans prompt supplémentaire
    $command = $global:textBox.Text
    $global:richTextBox.AppendText("$command`n") # Ajouter uniquement la commande

    # Effacer le TextBox après l'envoi
    $global:textBox.Clear()

    # Vérifier si la commande n'est pas vide
    if (-not [string]::IsNullOrWhiteSpace($command)) {
        try {
            # Fichiers temporaires pour capturer la sortie
            $outputFile = [System.IO.Path]::GetTempFileName()
            $errorFile = [System.IO.Path]::GetTempFileName()

            # Lancer la commande avec Start-Process
            Start-Process -FilePath "powershell.exe" `
                          -ArgumentList "-Command", $command `
                          -WindowStyle Hidden `
                          -RedirectStandardOutput $outputFile `
                          -RedirectStandardError $errorFile `
                          -Wait

            # Lire la sortie standard
            if (Test-Path $outputFile) {
                $output = Get-Content $outputFile
                if ($output) {
                    $global:richTextBox.AppendText("$output`n")
                }
                Remove-Item $outputFile -Force # Nettoyer après utilisation
            }

            # Lire la sortie d'erreur
            if (Test-Path $errorFile) {
                $errorOutput = Get-Content $errorFile
                if ($errorOutput) {
                    $global:richTextBox.AppendText("Erreur : $errorOutput`n")
                }
                Remove-Item $errorFile -Force # Nettoyer après utilisation
            }
        } catch {
            $global:richTextBox.AppendText("Erreur lors de l'exécution : $_`n")
        }
    }

    # Réafficher le prompt après la commande
    $global:richTextBox.AppendText("PS > ")
    $global:richTextBox.ScrollToCaret()
})

# Position initiale du prompt
$global:promptLength = $global:richTextBox.Text.Length

# Ajouter un bouton pour fermer l'onglet
$global:closeButton = Create-CloseButton

# Ajouter l'événement du bouton
$global:closeButton.Add_Click({

    # Récupérer l'onglet actuel
    $currentTab = $tabControl_API.SelectedTab

    $tabControl_API.TabPages.Remove($currentTab)
})

# Ajouter les contrôles à l'onglet
$newTab.Controls.Add($global:richTextBox)
$newTab.Controls.Add($global:textBox)
$newTab.Controls.Add($global:executeButton)
$newTab.Controls.Add($global:closeButton)
$global:closeButton.BringToFront()

# Ajouter l'onglet au TabControl
$tabControl_API.TabPages.Add($newTab)
$tabControl_API.SelectedTab = $newTab

})


# Créer le premier GroupBox avec les nouveaux boutons
$GroupBox1 = Create-GroupBox -Title "Connexion CPE" -ButtonTexts $ButtonTexts1 -ButtonActions $ButtonActions1 -BoxWidth 180 -BoxHeight 250

# Ajouter les GroupBox à la liste
$GroupBoxes += $GroupBox1

# Ajouter les GroupBox au formulaire
$API.Controls.AddRange($GroupBoxes)

<# ------------------ Ajout des objets dans l'onglet principal ------------------ #>

#Correction d'erreur :

# Vérifie si $GroupBoxes est un tableau ou un seul contrôle
if ($GroupBoxes -is [System.Collections.IEnumerable]) {
    foreach ($control in $GroupBoxes) {
        $tab_API.Controls.Add($control)
    }
} else {
    $tab_API.Controls.Add($GroupBoxes)
}


<# ------------------ Fin du Script ------------------ #>

# Afficher le formulaire
$API.ShowDialog()