Question
Je perd la valeur de mes variables !
- PERSIN
- Auteur du sujet
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 4
- Remerciements reçus 0
il y a 12 ans 8 mois #15308
par PERSIN
Je perd la valeur de mes variables ! a été créé par PERSIN
Bonjour,
Je débute en Powershell, et j'ai récupéré quelques bouts de scripts par ci par là pour créer un outils
qui me permettrai de lister la liste des fichiers sql pour les exécuter...
Or, lorsque je clique sur un bouton, je récupère bien le répertoire d'exécution (que je met dans une variable)
Lorsque je clique sur le bouton d'exécution, mes variables sont VIDES !!....
Pouvez-vous m'aider avec le script simplifié ci-dessous ??
Ai-je loupé quelquechose ??
Merci de votre AIDE !
function Choix_repertoire
{
$message ='Select a folder'
$path = \"c:\repertoire_sql\"
$object = New-Object -comObject Shell.Application
$folder = $object.BrowseForFolder(0, $message, 0, $path)
if ($folder -ne $null)
{
$liste = Get-ChildItem -path $folder.self.Path -recurse -filter \"*.sql\"
}
$rep_travail = $folder.self.path
$nb_occurence = $liste.count
$outputBox.Text = \"\"
$outputBox.Appendtext(($liste | Out-String ))
Write-Host \"Choose : Répertoire de travail \" $rep_travail
Write-Host \"Choose : Nombre d'occurence \" $nb_occurence
}
Function Execution_bouton
{
Write-Host \"Exec : Répertoire de travail \" $repertoire
Write-Host \"Exec : Nombre d'occurence \" $nb_occurence
}
function GenerateForm {
[reflection.assembly]::loadwithpartialname(\"System.Windows.Forms\") | Out-Null
[reflection.assembly]::loadwithpartialname(\"System.Drawing\") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#
#Generated Event Script Blocks
#
$OnLoadForm_StateCorrection=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#
#region Generated Form Code
$form1.Text = \"SQL Executor\"
$form1.Name = \"form1\"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 830
$System_Drawing_Size.Height = 536
$form1.ClientSize = $System_Drawing_Size
$button1.TabIndex = 4
$button1.Name = \"button1\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True
$button1.Text = \"Choose Folder\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 30
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click({Choix_repertoire})
$form1.Controls.Add($button1)
$button2.TabIndex = 4
$button2.Name = \"button2\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button2.Size = $System_Drawing_Size
$button2.UseVisualStyleBackColor = $True
$button2.Text = \"Execute Sql\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 65
$button2.Location = $System_Drawing_Point
$button2.DataBindings.DefaultDataSourceUpdateMode = 0
$button2.add_Click({Execution_bouton})
$form1.Controls.Add($button2)
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(137,13)
$outputBox.Size = New-Object System.Drawing.Size(650,512)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = \"Vertical\"
$Form1.Controls.Add($outputBox)
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
#Declaration varibales Globales
$global:nb_occurence = 0
$global:repertoire = \" \"
#Call the Function
GenerateForm
Je débute en Powershell, et j'ai récupéré quelques bouts de scripts par ci par là pour créer un outils
qui me permettrai de lister la liste des fichiers sql pour les exécuter...
Or, lorsque je clique sur un bouton, je récupère bien le répertoire d'exécution (que je met dans une variable)
Lorsque je clique sur le bouton d'exécution, mes variables sont VIDES !!....
Pouvez-vous m'aider avec le script simplifié ci-dessous ??
Ai-je loupé quelquechose ??
Merci de votre AIDE !
function Choix_repertoire
{
$message ='Select a folder'
$path = \"c:\repertoire_sql\"
$object = New-Object -comObject Shell.Application
$folder = $object.BrowseForFolder(0, $message, 0, $path)
if ($folder -ne $null)
{
$liste = Get-ChildItem -path $folder.self.Path -recurse -filter \"*.sql\"
}
$rep_travail = $folder.self.path
$nb_occurence = $liste.count
$outputBox.Text = \"\"
$outputBox.Appendtext(($liste | Out-String ))
Write-Host \"Choose : Répertoire de travail \" $rep_travail
Write-Host \"Choose : Nombre d'occurence \" $nb_occurence
}
Function Execution_bouton
{
Write-Host \"Exec : Répertoire de travail \" $repertoire
Write-Host \"Exec : Nombre d'occurence \" $nb_occurence
}
function GenerateForm {
[reflection.assembly]::loadwithpartialname(\"System.Windows.Forms\") | Out-Null
[reflection.assembly]::loadwithpartialname(\"System.Drawing\") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#
#Generated Event Script Blocks
#
$OnLoadForm_StateCorrection=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#
#region Generated Form Code
$form1.Text = \"SQL Executor\"
$form1.Name = \"form1\"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 830
$System_Drawing_Size.Height = 536
$form1.ClientSize = $System_Drawing_Size
$button1.TabIndex = 4
$button1.Name = \"button1\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True
$button1.Text = \"Choose Folder\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 30
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click({Choix_repertoire})
$form1.Controls.Add($button1)
$button2.TabIndex = 4
$button2.Name = \"button2\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button2.Size = $System_Drawing_Size
$button2.UseVisualStyleBackColor = $True
$button2.Text = \"Execute Sql\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 65
$button2.Location = $System_Drawing_Point
$button2.DataBindings.DefaultDataSourceUpdateMode = 0
$button2.add_Click({Execution_bouton})
$form1.Controls.Add($button2)
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(137,13)
$outputBox.Size = New-Object System.Drawing.Size(650,512)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = \"Vertical\"
$Form1.Controls.Add($outputBox)
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
#Declaration varibales Globales
$global:nb_occurence = 0
$global:repertoire = \" \"
#Call the Function
GenerateForm
Connexion ou Créer un compte pour participer à la conversation.
- Matthew BETTON
- Hors Ligne
- Membre platinium
-
Réduire
Plus d'informations
- Messages : 968
- Remerciements reçus 0
il y a 12 ans 8 mois #15309
par Matthew BETTON
Réponse de Matthew BETTON sur le sujet Re:Je perd la valeur de mes variables !
Bonjour,
Ta fonction 'Execution_Bouton' ne connait pas les variables '$repertoire' et '$nb_occurence'.
Il est préférable que tu lui passes en paramètres lors de son appelle.
Comme tu utilises des variables globales (attention, il me semble qu'il y a un problème de nommage avec '$repertoire' qui devrait être '$rep_travail') :
[code:1]
#Declaration varibales Globales
$global:nb_occurence = 0
$global:rep_travail = \" \"
[/code:1]
Dans les différentes fonctions, si tu veux modifier ces variables globales, tu dois toujours préciser qu'elles le sont, sinon il s'agit d'une variable isolée dont la portée ne concerne que la fonction...
[code:1]
function Choix_repertoire
{
$message ='Select a folder'
$path = \"c:\\"
$object = New-Object -comObject Shell.Application
$folder = $object.BrowseForFolder(0, $message, 0, $path)
if ($folder -ne $null)
{
$liste = Get-ChildItem -path $folder.self.Path -recurse -filter \"*.sql\"
}
$global:rep_travail = $folder.self.path
$global:nb_occurence = $liste.count
$outputBox.Text = \"\"
$outputBox.Appendtext(($liste | Out-String ))
Write-Host \"Choose : Répertoire de travail \" $global:rep_travail
Write-Host \"Choose : Nombre d'occurence \" $global:nb_occurence
}
Function Execution_bouton
{
Write-Host \"Exec : Répertoire de travail \" $global:rep_travail
Write-Host \"Exec : Nombre d'occurence \" $global:nb_occurence
}
function GenerateForm {
[reflection.assembly]::loadwithpartialname(\"System.Windows.Forms\"«») | Out-Null
[reflection.assembly]::loadwithpartialname(\"System.Drawing\"«») | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#
#Generated Event Script Blocks
#
$OnLoadForm_StateCorrection=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#
#region Generated Form Code
$form1.Text = \"SQL Executor\"
$form1.Name = \"form1\"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 830
$System_Drawing_Size.Height = 536
$form1.ClientSize = $System_Drawing_Size
$button1.TabIndex = 4
$button1.Name = \"button1\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True
$button1.Text = \"Choose Folder\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 30
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click({Choix_repertoire})
$form1.Controls.Add($button1)
$button2.TabIndex = 4
$button2.Name = \"button2\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button2.Size = $System_Drawing_Size
$button2.UseVisualStyleBackColor = $True
$button2.Text = \"Execute Sql\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 65
$button2.Location = $System_Drawing_Point
$button2.DataBindings.DefaultDataSourceUpdateMode = 0
$button2.add_Click({Execution_bouton})
$form1.Controls.Add($button2)
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(137,13)
$outputBox.Size = New-Object System.Drawing.Size(650,512)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = \"Vertical\"
$Form1.Controls.Add($outputBox)
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
#Declaration varibales Globales
$global:nb_occurence = 0
$global:rep_travail = \" \"
#Call the Function
GenerateForm
[/code:1]
Mais il faut éviter de jouer avec des variables globales => Sources d'erreur...
Un bloc 'param()' permet de définir les paramètres de ta fonction :
[code:1]
Function Execution_bouton
{
param(
[String]$Path,
[String]$oc
)
Write-Host \"Exec : Répertoire de travail \" $Path
Write-Host \"Exec : Nombre d'occurence \" $oc
}
[/code:1]
Ensuite, lors de l'appelle de la fonction, tu passes les valeurs comme paramètres :
[code:1]
$button2.add_Click({Execution_bouton $rep_travail $nb_occurence})
[/code:1]
ou
[code:1]
$button2.add_Click({Execution_bouton $global:rep_travail $global:nb_occurence})
[/code:1]
Tu peux aussi rendre obligatoires les paramètres en modifiant le bloc param() :
[code:1]
param(
[Parameter(Mandatory=$true)]
[String]$Path,
[Parameter(Mandatory=$true)]
[String]$oc
)
[/code:1]
Ensuite tes fonctions doivent retourner le ou les résultats (valeurs calculées, modifiées, ...) via un 'return' ...
@ +
Matthew BETTON
Ta fonction 'Execution_Bouton' ne connait pas les variables '$repertoire' et '$nb_occurence'.
Il est préférable que tu lui passes en paramètres lors de son appelle.
Comme tu utilises des variables globales (attention, il me semble qu'il y a un problème de nommage avec '$repertoire' qui devrait être '$rep_travail') :
[code:1]
#Declaration varibales Globales
$global:nb_occurence = 0
$global:rep_travail = \" \"
[/code:1]
Dans les différentes fonctions, si tu veux modifier ces variables globales, tu dois toujours préciser qu'elles le sont, sinon il s'agit d'une variable isolée dont la portée ne concerne que la fonction...
[code:1]
function Choix_repertoire
{
$message ='Select a folder'
$path = \"c:\\"
$object = New-Object -comObject Shell.Application
$folder = $object.BrowseForFolder(0, $message, 0, $path)
if ($folder -ne $null)
{
$liste = Get-ChildItem -path $folder.self.Path -recurse -filter \"*.sql\"
}
$global:rep_travail = $folder.self.path
$global:nb_occurence = $liste.count
$outputBox.Text = \"\"
$outputBox.Appendtext(($liste | Out-String ))
Write-Host \"Choose : Répertoire de travail \" $global:rep_travail
Write-Host \"Choose : Nombre d'occurence \" $global:nb_occurence
}
Function Execution_bouton
{
Write-Host \"Exec : Répertoire de travail \" $global:rep_travail
Write-Host \"Exec : Nombre d'occurence \" $global:nb_occurence
}
function GenerateForm {
[reflection.assembly]::loadwithpartialname(\"System.Windows.Forms\"«») | Out-Null
[reflection.assembly]::loadwithpartialname(\"System.Drawing\"«») | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#
#Generated Event Script Blocks
#
$OnLoadForm_StateCorrection=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#
#region Generated Form Code
$form1.Text = \"SQL Executor\"
$form1.Name = \"form1\"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 830
$System_Drawing_Size.Height = 536
$form1.ClientSize = $System_Drawing_Size
$button1.TabIndex = 4
$button1.Name = \"button1\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True
$button1.Text = \"Choose Folder\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 30
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click({Choix_repertoire})
$form1.Controls.Add($button1)
$button2.TabIndex = 4
$button2.Name = \"button2\"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$button2.Size = $System_Drawing_Size
$button2.UseVisualStyleBackColor = $True
$button2.Text = \"Execute Sql\"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 65
$button2.Location = $System_Drawing_Point
$button2.DataBindings.DefaultDataSourceUpdateMode = 0
$button2.add_Click({Execution_bouton})
$form1.Controls.Add($button2)
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(137,13)
$outputBox.Size = New-Object System.Drawing.Size(650,512)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = \"Vertical\"
$Form1.Controls.Add($outputBox)
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
#Declaration varibales Globales
$global:nb_occurence = 0
$global:rep_travail = \" \"
#Call the Function
GenerateForm
[/code:1]
Mais il faut éviter de jouer avec des variables globales => Sources d'erreur...
Un bloc 'param()' permet de définir les paramètres de ta fonction :
[code:1]
Function Execution_bouton
{
param(
[String]$Path,
[String]$oc
)
Write-Host \"Exec : Répertoire de travail \" $Path
Write-Host \"Exec : Nombre d'occurence \" $oc
}
[/code:1]
Ensuite, lors de l'appelle de la fonction, tu passes les valeurs comme paramètres :
[code:1]
$button2.add_Click({Execution_bouton $rep_travail $nb_occurence})
[/code:1]
ou
[code:1]
$button2.add_Click({Execution_bouton $global:rep_travail $global:nb_occurence})
[/code:1]
Tu peux aussi rendre obligatoires les paramètres en modifiant le bloc param() :
[code:1]
param(
[Parameter(Mandatory=$true)]
[String]$Path,
[Parameter(Mandatory=$true)]
[String]$oc
)
[/code:1]
Ensuite tes fonctions doivent retourner le ou les résultats (valeurs calculées, modifiées, ...) via un 'return' ...
@ +
Matthew BETTON
Connexion ou Créer un compte pour participer à la conversation.
- PERSIN
- Auteur du sujet
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 4
- Remerciements reçus 0
il y a 12 ans 8 mois #15311
par PERSIN
Réponse de PERSIN sur le sujet Re:Je perd la valeur de mes variables !
Merci Mathew pour ta réactivité !!
Effectivement, je n'ai pas précisé dans la fonction que les variables étaient globales !!
Du coup en les déclarant globales, ça marche très bien !!
Tu conseilles cependant d'éviter les variables globales, je vais essayer les autres méthodes que tu as proposé un peu plus tard...
Encore merci pour la leçon !!
Effectivement, je n'ai pas précisé dans la fonction que les variables étaient globales !!
Du coup en les déclarant globales, ça marche très bien !!
Tu conseilles cependant d'éviter les variables globales, je vais essayer les autres méthodes que tu as proposé un peu plus tard...
Encore merci pour la leçon !!
Connexion ou Créer un compte pour participer à la conversation.
- Laurent Dardenne
- Hors Ligne
- Modérateur
-
Réduire
Plus d'informations
- Messages : 6311
- Remerciements reçus 68
il y a 12 ans 8 mois #15316
par Laurent Dardenne
Tutoriels PowerShell
Réponse de Laurent Dardenne sur le sujet Re:Je perd la valeur de mes variables !
sybcat écrit:
Variable globales, emmerdes globales...Tu conseilles cependant d'éviter les variables globales, je vais essayer les autres méthodes que tu as proposé un peu plus tard...
Tutoriels PowerShell
Connexion ou Créer un compte pour participer à la conversation.
Temps de génération de la page : 0.046 secondes
- Vous êtes ici :
-
Accueil
-
forum
-
PowerShell
-
Entraide pour les débutants
- Je perd la valeur de mes variables !