need help with variable

hi there

in my script the variable wont work some one can help ??

variable in probleme are $Textbox 1, 2, 3, 4

 

When i click create the variable not working

 

CODE START

Add-Type -AssemblyName System.Windows.Forms

Add-Type -AssemblyName System.Drawing

 

Function AddEm

{

$TextBox4.Text = $TextBox1.Text + " " + $TextBox2.Text

$Textbox3.Visible = $true

$Textbox3.Text = $Textbox1.Text[0] + “” + $Textbox2.Text + @email.com

$Textbox3.Visible = $true

}

 

Function MakeForm

{

$script:Form1 = New-Object system.Windows.Forms.Form

$Form1.Text = “Add Mail box”

$Font = New-Object System.Drawing.Font(“Times New Roman”, 12, [System.Drawing.FontStyle]::Bold)

$Form1.Font = $Font

$label = New-Object Windows.Forms.Label

$label.Location = New-Object Drawing.Point 150, 80

$label.Size = New-Object Drawing.Point 200, 25

$label.text = “First Name”

$Form1.Controls.Add($label)

$script:TextBox1 = New-Object System.Windows.Forms.Textbox

$TextBox1.Location = New-Object System.Drawing.Size(5, 80)

$TextBox1.Size = New-Object System.Drawing.Size(100, 40)

$label = New-Object Windows.Forms.Label

$label.Location = New-Object Drawing.Point 150, 113

$label.Size = New-Object Drawing.Point 200, 25

$label.text = “Name”

$Form1.Controls.Add($label)

$script:TextBox2 = New-Object System.Windows.Forms.Textbox

$TextBox2.Location = New-Object System.Drawing.Size(5, 110)

$TextBox2.Size = New-Object System.Drawing.Size(100, 40)

$label = New-Object Windows.Forms.Label

$label.Location = New-Object Drawing.Point 150, 143

$label.Size = New-Object Drawing.Point 200, 25

$label.text = “Full Name”

$Form1.Controls.Add($label)

$script:TextBox4 = New-Object System.Windows.Forms.Textbox

$TextBox4.Location = New-Object System.Drawing.Size(5, 140)

$TextBox4.Size = New-Object System.Drawing.Size(120, 40)

$script:TextBox3 = New-Object System.Windows.Forms.Textbox

$TextBox3.Location = New-Object System.Drawing.Size(5, 210)

$TextBox3.Size = New-Object System.Drawing.Size(200, 40)

$TextBox3.Visible = $false

$Button1 = New-Object System.Windows.Forms.Button

$Button1.Location = New-Object System.Drawing.Size(95, 20)

$Button1.Size = New-Object System.Drawing.Size(80, 50)

$Button1.Text = “Create”

$Button1.Add_Click({

Set-ExecutionPolicy Unrestricted -Scope Process -Force

$Username = “admin@.onmicrosoft.com”

$Password = ConvertTo-SecureString ‘Password’ -AsPlainText -Force

$LiveCred = New-Object System.Management.Automation.PSCredential $Username, $Password

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $LiveCred -Authentication Basic -AllowRedirection

Import-PSSession $Session

Connect-MsolService -Credential $LiveCred

Import-Module MSOnline

Get-MsolUser

New-MsolUser -UserPrincipalName “$Textbox3” -FirstName “$textbox1” -LastName “$textbox2” -DisplayName “$textbox4” -UsageLocation CA

Set-MsolUserPassword -UserPrincipalname “$Textbox3” -NewPassword “$password1”

$forcechange = Read-Host “force a changer Y/N”

if ($forcechange -eq “n”)

{

Set-MsolUserPassword -UserPrincipalName “$Textbox3” -NewPassWord “$nouveaupass” -ForceChangePassword $false

}

else

{

Set-MsolUserPassword -UserPrincipalName “$Textbox3” -NewPassWord “$nouveaupass” -ForceChangePassword $true

}

Get-MsolAccountSku

$LicenseSKU = Get-MsolAccountSku | Out-GridView -Title ‘Select a license plan to assign to users’ -OutputMode Single | Select-Object -ExpandProperty AccountSkuId

$x = Get-MsolUser -All -UnlicensedUsersOnly | Out-GridView -Title ‘Select users to assign license plan to’ -OutputMode Multiple

$x | Set-MsolUser -UsageLocation CA

$x | Set-MsolUserLicense -AddLicenses $LicenseSKU

})

$Button2 = New-Object System.Windows.Forms.Button

$Button2.Location = New-Object System.Drawing.Size(5, 20)

$Button2.Size = New-Object System.Drawing.Size(80, 50)

$Button2.Text = “Creation email”

$Button2.Add_Click({ AddEm })

$Button3 = New-Object System.Windows.Forms.Button

$Button3.Location = New-Object System.Drawing.Size(185, 20)

$Button3.Size = New-Object System.Drawing.Size(80, 50)

$Button3.Text = “Exit”

$Button3.Add_Click({ $Form1.Close() })

$Form1.Controls.Add($Button1)

$Form1.Controls.Add($Button2)

$Form1.Controls.Add($Button3)

$Form1.Controls.Add($TextBox1)

$Form1.Controls.Add($TextBox2)

$Form1.Controls.Add($TextBox3)

$Form1.Controls.Add($TextBox4)

$Form1.ShowDialog()

}

$Button6 = New-Object System.Windows.Forms.Button

$Button6.Location = New-Object System.Drawing.Size(25, 15)

$Button6.Size = New-Object System.Drawing.Size(110, 23)

$Button6.Text = “Créé Usager”

$Button6.Add_Click({ MakeForm -form1 })

Add-Type -AssemblyName System.Windows.Forms

Add-Type -AssemblyName System.Drawing

# Build Form

$Form = New-Object System.Windows.Forms.Form

$Form.Text = “O365 Manager”

$Form.Size = New-Object System.Drawing.Size(800, 800)

$Form.StartPosition = “CenterScreen”

$Form.Topmost = $false

$form.Controls.Add($Button6)

$form.Controls.Add($Button7)

#Add Button event

$Button6.Add_Click($Button6)

$Button7.Add_Click($Button7)

$form.ShowDialog()

Before all, can you please go through below post and format the code using the instructions ? that will be helpfull.

https://powershell.org/forums/topic/read-me-before-posting-youll-be-glad-you-did/

  • What editor are you using to code this?
  • Why are you not using debug mode to trap breakpoints to see what is and is not being fired / happening?

There is more wrong with the code you posted than just those button you mention. So, step back and review, one segment at a time. Get in the habit of using this in your PS/ISE/VSCode user profiles …

Set-StrictMode  -Version Latest 

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-strictmode
… so, that you don’t trip up on undeclared things, and the like in your dev cycle.

  • Why are the txt boxes not properly ordered?
  • Why is TextBox4 not complete?
  • Why are you only showing the 'Create User' button on form load?
  • Why are you forcing users to click the create button to populate the rest of the four objects.
  • What are you using to create this form?

If you are doing this by hand, don’t if you want to save yourself the headache that you appear to be having now. Use this site https://poshgui.com/Editor, as it’s a drug and drop GI from builder for PowerShell, or download and use Visual Studio Community Edition https://visualstudio.microsoft.com/vs/community to do your from work.

Errors which show up when this is ran (because there is no button7):

Exception             : System.Management.Automation.RuntimeException: The variable '$Button7' cannot be retrieved because it has not been set.
                           at System.Management.Automation.VariableOps.GetVariableValue(VariablePath variablePath, ExecutionContext 
                        executionContext, VariableExpressionAst varAst)
                           at System.Management.Automation.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          : Button7
CategoryInfo          : InvalidOperation: (Button7:String) [], RuntimeException
FullyQualifiedErrorId : VariableIsUndefined
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 176
PipelineIterationInfo : {}
PSMessageDetails      : 

Exception             : System.Management.Automation.MethodException: Cannot convert argument "value", with value: 
                        "System.Windows.Forms.Button, Text: Créé Usager", for "add_Click" to type "System.EventHandler": "Cannot convert the 
                        "System.Windows.Forms.Button, Text: Créé Usager" value of type "System.Windows.Forms.Button" to type 
                        "System.EventHandler"." ---> System.Management.Automation.PSInvalidCastException: Cannot convert the 
                        "System.Windows.Forms.Button, Text: Créé Usager" value of type "System.Windows.Forms.Button" to type 
                        "System.EventHandler".
                           at System.Management.Automation.LanguagePrimitives.ThrowInvalidCastException(Object valueToConvert, Type resultType)
                           at System.Management.Automation.LanguagePrimitives.ConvertNoConversion(Object valueToConvert, Type resultType, 
                        Boolean recurse, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
                           at CallSite.Target(Closure , CallSite , Object , Object )
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.ConvertToArgumentConversionException(Exception exception, 
                        String parameterName, Object argument, String method, Type toType)
                           at CallSite.Target(Closure , CallSite , Object , Object )
                           at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
                           at System.Management.Automation.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          : 
CategoryInfo          : NotSpecified: (:) [], MethodException
FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 175
PipelineIterationInfo : {}
PSMessageDetails      : 

Exception             : System.Management.Automation.RuntimeException: The variable '$Button7' cannot be retrieved because it has not been set.
                           at System.Management.Automation.VariableOps.GetVariableValue(VariablePath variablePath, ExecutionContext 
                        executionContext, VariableExpressionAst varAst)
                           at System.Management.Automation.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          : Button7
CategoryInfo          : InvalidOperation: (Button7:String) [], RuntimeException
FullyQualifiedErrorId : VariableIsUndefined
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 172
PipelineIterationInfo : {}
PSMessageDetails      : 

Your code refactored to be a bit more readable to show every place you either are missing code, or miscoded the entry. Always remember to do this when you post here and use the format tools. Also, never ever use plain text passwords in scripts. You are just adding risks you don’t need. Always prompt for them or create them securing and call them as needed.

'System.Windows.Forms','System.Drawing' | 
ForEach{Add-Type -AssemblyName $PSItem}

Function AddEm
{
    $TextBox4.Text = $TextBox1.Text + " " + $TextBox2.Text
    $Textbox3.Visible = $true
    $Textbox3.Text = $Textbox1.Text[0] + "" + $Textbox2.Text + "@email.com"
    $Textbox3.Visible = $true
}

Function MakeForm
{
    $script:Form1 = New-Object system.Windows.Forms.Form
    $Form1.Text = "Add Mail box"

    $Font = New-Object System.Drawing.Font("Times New Roman", 12, [System.Drawing.FontStyle]::Bold)

    $Form1.Font = $Font

    $label = New-Object Windows.Forms.Label
    $label.Location = New-Object Drawing.Point 150, 80
    $label.Size = New-Object Drawing.Point 200, 25
    $label.text = "First Name"

    $Form1.Controls.Add($label)

    $script:TextBox1 = New-Object System.Windows.Forms.Textbox
    $TextBox1.Location = New-Object System.Drawing.Size(5, 80)
    $TextBox1.Size = New-Object System.Drawing.Size(100, 40)

    $label = New-Object Windows.Forms.Label
    $label.Location = New-Object Drawing.Point 150, 113
    $label.Size = New-Object Drawing.Point 200, 25
    $label.text = "Name"

    $Form1.Controls.Add($label) 

    $script:TextBox2 = New-Object System.Windows.Forms.Textbox
    $TextBox2.Location = New-Object System.Drawing.Size(5, 110)
    $TextBox2.Size = New-Object System.Drawing.Size(100, 40)

    $label = New-Object Windows.Forms.Label
    $label.Location = New-Object Drawing.Point 150, 143
    $label.Size = New-Object Drawing.Point 200, 25
    $label.text = "Full Name"

    $Form1.Controls.Add($label) 

    $script:TextBox4 = New-Object System.Windows.Forms.Textbox
    $TextBox4.Location = New-Object System.Drawing.Size(5, 140)
    $TextBox4.Size = New-Object System.Drawing.Size(120, 40)

    $script:TextBox3 = New-Object System.Windows.Forms.Textbox
    $TextBox3.Location = New-Object System.Drawing.Size(5, 210)
    $TextBox3.Size = New-Object System.Drawing.Size(200, 40)
    $TextBox3.Visible = $false

    $Button1 = New-Object System.Windows.Forms.Button
    $Button1.Location = New-Object System.Drawing.Size(95, 20)
    $Button1.Size = New-Object System.Drawing.Size(80, 50)
    $Button1.Text = "Create"

    $Button1.Add_Click( { 
            Set-ExecutionPolicy Unrestricted -Scope Process -Force

            $Username = "admin@.onmicrosoft.com"
            $Password = ConvertTo-SecureString 'Password' -AsPlainText -Force

            $LiveCred = New-Object System.Management.Automation.PSCredential $Username, $Password

            $newPSSessionSplat = @{
                Credential = $LiveCred
                ConnectionUri = 'https://outlook.office365.com/powershell-liveid/'
                AllowRedirection = $true
                Authentication = 'Basic'
                ConfigurationName = 'Microsoft.Exchange'
            }
            $Session = New-PSSession @newPSSessionSplat
            Import-PSSession $Session

            Connect-MsolService -Credential $LiveCred

            Import-Module MSOnline
            Get-MsolUser

            $newMsolUserSplat = @{
                UsageLocation = 'CA'
                DisplayName = "$textbox4"
                FirstName = "$textbox1"
                UserPrincipalName = "$Textbox3"
                LastName = "$textbox2"
            }
            New-MsolUser @newMsolUserSplat

            Set-MsolUserPassword -UserPrincipalname "$Textbox3" -NewPassword "$password1"

            $forcechange = Read-Host "force a changer Y/N"

            if ($forcechange -eq "n")
            {
                $setMsolUserPasswordSplat = @{
                    NewPassWord = "$nouveaupass"
                    ForceChangePassword = $false
                    UserPrincipalName = "$Textbox3"
                }
                Set-MsolUserPassword @setMsolUserPasswordSplat
            }
            else
            {
                $setMsolUserPasswordSplat = @{
                    NewPassWord = "$nouveaupass"
                    ForceChangePassword = $true
                    UserPrincipalName = "$Textbox3"
                }
                Set-MsolUserPassword @setMsolUserPasswordSplat
            }

            Get-MsolAccountSku

            $LicenseSKU = Get-MsolAccountSku | 
            Out-GridView -Title 'Select a license plan to assign to users' -OutputMode Single | 
            Select-Object -ExpandProperty AccountSkuId
            
            $x = Get-MsolUser -All -UnlicensedUsersOnly | 
            Out-GridView -Title 'Select users to assign license plan to' -OutputMode Multiple

            $x | Set-MsolUser -UsageLocation CA
            $x | Set-MsolUserLicense -AddLicenses $LicenseSKU
        })

    $Button2 = New-Object System.Windows.Forms.Button
    $Button2.Location = New-Object System.Drawing.Size(5, 20)
    $Button2.Size = New-Object System.Drawing.Size(80, 50)
    $Button2.Text = "Creation email"
    $Button2.Add_Click( { AddEm })

    $Button3 = New-Object System.Windows.Forms.Button
    $Button3.Location = New-Object System.Drawing.Size(185, 20)
    $Button3.Size = New-Object System.Drawing.Size(80, 50)
    $Button3.Text = "Exit"
    $Button3.Add_Click( { $Form1.Close() })

    $Form1.Controls.Add($Button1)
    $Form1.Controls.Add($Button2)
    $Form1.Controls.Add($Button3)
    $Form1.Controls.Add($TextBox1)
    $Form1.Controls.Add($TextBox2)
    $Form1.Controls.Add($TextBox3)
    $Form1.Controls.Add($TextBox4)
    $Form1.ShowDialog()
}

$Button6 = New-Object System.Windows.Forms.Button
$Button6.Location = New-Object System.Drawing.Size(25, 15)
$Button6.Size = New-Object System.Drawing.Size(110, 23)
$Button6.Text = "Créé Usager"
$Button6.Add_Click( { MakeForm -form1 })

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# Build Form
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "O365 Manager"
$Form.Size = New-Object System.Drawing.Size(800, 800)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $false
$form.Controls.Add($Button6)
$form.Controls.Add($Button7)

#Add Button event 
$Button6.Add_Click($Button6)
$Button7.Add_Click($Button7)
$form.ShowDialog()