none
Объясните пожалуйста, как добавить действие на кнопку RRS feed

  • Вопрос

  • Добрый день, не могу понять как сделать так, чтобы при нажатии на кнопку на форме выполнялся код. Добавляю действие, но ничего не происходит:

    $ButtonCreate.Add_Click({
    if ($LangLabelBox.SelectedItem = "EN") {
    
    $Country = 010
    & 'C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1'
    Connect-VIServer -Server server -User root -Password 
    $Spec=Get-OSCustomizationSpec -Name $LangLabelBox.SelectedItem
    if ($Spec -ne $null)
    
    <....>
    
    Start-Sleep -Seconds 30
    $Time = 0
    do {
        $UpTime = Get-Stat -Entity $HostNameTextbox.Text -Stat sys.uptime.latest -Realtime -MaxSamples 1
        $Time = $UpTime.Value
        $Time
        }
        until ($Time -gt 600)
    
    Get-VM -Name $HostNameTextbox.Text | %{$IPAddress = $_.Guest.IPAddress[0]}
    
    
    [System.Windows.Forms.MessageBox]::Show("Create VM successfully")
    }
    })


    С уважением, Спицкий Никита

Ответы

Все ответы

  • Что такое $Buttoncreate?

    Если это взято из статьи укажите онную.

    Что вообще должно происходить?

    Опишите в кратце тз


    The opinion expressed by me is not an official position of Microsoft

    Модератор
  • Обычная переменная:

    $ButtonCreate = New-Object System.Windows.Forms.Button
    $ButtonCreate.Location = New-Object System.Drawing.Size(100,290)
    $ButtonCreate.Text = "Create VM"
    $ButtonCreate.Size = New-Object System.Drawing.Size(70,20)
    $MainForm.Controls.Add($ButtonCreate)

    Должно происходить подключение к VMWARE и создание виртуальной машины из шаблона


    С уважением, Спицкий Никита

  • Полный код покажите.
    Отвечающий
  • #robot chappy ver. 1.0 Add-Type -AssemblyName System.Windows.Forms $MainForm = New-Object System.Windows.Forms.Form $MainForm.Width = 250 $MainForm.Height = 350 $MainForm.FormBorderStyle = "Fixed3D" $MainForm.MinimizeBox = $false $MainForm.MaximizeBox = $false $MainForm.Text = "AM Chappy" $MainForm.StartPosition = "CenterScreen" #label chappe #label $HostAddressLabel = New-Object System.Windows.Forms.Label $HostAddressLabel.Location = New-Object System.Drawing.Point (5,10) $HostAddressLabel.Text = "AM-Chappy" $MainForm.Controls.Add($HostAddressLabel) #Generate random string for password function AdministratorPassword() { Param ( [int]$length = 8, [bool] $includeLowercaseLetters = $true, [bool] $includeUppercaseLetters = $true, [bool] $includeNumbers = $true, [bool] $includeSpecialChars = $false, [bool] $noSimilarCharacters = $true ) <# (c) Morgan de Jonge CC BY SA Generates a random password. you're able to specify: - The desired password length (minimum = 4) - Whether or not to use lowercase characters - Whether or not to use uppercase characters - Whether or not to use numbers - Whether or not to use special characters - Whether or not to avoid using similar characters ( e.g. i, l, o, 1, 0, I) #> # Validate params if($length -lt 4) { $exception = New-Object Exception "The minimum password length is 4" Throw $exception } if ($includeLowercaseLetters -eq $false -and $includeUppercaseLetters -eq $false -and $includeNumbers -eq $false -and $includeSpecialChars -eq $false) { $exception = New-Object Exception "At least one set of included characters must be specified" Throw $exception } #Available characters $CharsToSkip = [char]"i", [char]"l", [char]"o", [char]"1", [char]"0", [char]"I" $AvailableCharsForPassword = $null; $uppercaseChars = $null for($a = 65; $a -le 90; $a++) { if($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) {$uppercaseChars += ,[char][byte]$a }} $lowercaseChars = $null for($a = 97; $a -le 122; $a++) { if($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) {$lowercaseChars += ,[char][byte]$a }} $digitChars = $null for($a = 48; $a -le 57; $a++) { if($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) {$digitChars += ,[char][byte]$a }} $specialChars = $null $specialChars += [char]"=", [char]"+", [char]"_", [char]"?", [char]"!", [char]"-", [char]"#", [char]"$", [char]"*", [char]"&", [char]"@" $TemplateLetters = $null if($includeLowercaseLetters) { $TemplateLetters += "L" } if($includeUppercaseLetters) { $TemplateLetters += "U" } if($includeNumbers) { $TemplateLetters += "N" } if($includeSpecialChars) { $TemplateLetters += "S" } $PasswordTemplate = @() # Set password template, to ensure that required chars are included do { $PasswordTemplate.Clear() for($loop = 1; $loop -le $length; $loop++) { $PasswordTemplate += $TemplateLetters.Substring((Get-Random -Maximum $TemplateLetters.Length),1) } } while (( (($includeLowercaseLetters -eq $false) -or ($PasswordTemplate -contains "L")) -and (($includeUppercaseLetters -eq $false) -or ($PasswordTemplate -contains "U")) -and (($includeNumbers -eq $false) -or ($PasswordTemplate -contains "N")) -and (($includeSpecialChars -eq $false) -or ($PasswordTemplate -contains "S"))) -eq $false ) #$PasswordTemplate now contains an array with at least one of each included character type (uppercase, lowercase, number and/or special) foreach($char in $PasswordTemplate) { switch ($char) { L { $Password += $lowercaseChars | Get-Random } U { $Password += $uppercaseChars | Get-Random } N { $Password += $digitChars | Get-Random } S { $Password += $specialChars | Get-Random } } } return $Password } function UserPassword() { Param ( [int]$length = 8, [bool] $includeLowercaseLetters = $true, [bool] $includeUppercaseLetters = $true, [bool] $includeNumbers = $true, [bool] $includeSpecialChars = $false, [bool] $noSimilarCharacters = $true ) <# (c) Morgan de Jonge CC BY SA Generates a random password. you're able to specify: - The desired password length (minimum = 4) - Whether or not to use lowercase characters - Whether or not to use uppercase characters - Whether or not to use numbers - Whether or not to use special characters - Whether or not to avoid using similar characters ( e.g. i, l, o, 1, 0, I) #> # Validate params if($length -lt 4) { $exception = New-Object Exception "The minimum password length is 4" Throw $exception } if ($includeLowercaseLetters -eq $false -and $includeUppercaseLetters -eq $false -and $includeNumbers -eq $false -and $includeSpecialChars -eq $false) { $exception = New-Object Exception "At least one set of included characters must be specified" Throw $exception } #Available characters $CharsToSkip = [char]"i", [char]"l", [char]"o", [char]"1", [char]"0", [char]"I" $AvailableCharsForPassword = $null; $uppercaseChars = $null for($a = 65; $a -le 90; $a++) { if($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) {$uppercaseChars += ,[char][byte]$a }} $lowercaseChars = $null for($a = 97; $a -le 122; $a++) { if($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) {$lowercaseChars += ,[char][byte]$a }} $digitChars = $null for($a = 48; $a -le 57; $a++) { if($noSimilarCharacters -eq $false -or [char][byte]$a -notin $CharsToSkip) {$digitChars += ,[char][byte]$a }} $specialChars = $null $specialChars += [char]"=", [char]"+", [char]"_", [char]"?", [char]"!", [char]"-", [char]"#", [char]"$", [char]"*", [char]"&", [char]"@" $TemplateLetters = $null if($includeLowercaseLetters) { $TemplateLetters += "L" } if($includeUppercaseLetters) { $TemplateLetters += "U" } if($includeNumbers) { $TemplateLetters += "N" } if($includeSpecialChars) { $TemplateLetters += "S" } $PasswordTemplate = @() # Set password template, to ensure that required chars are included do { $PasswordTemplate.Clear() for($loop = 1; $loop -le $length; $loop++) { $PasswordTemplate += $TemplateLetters.Substring((Get-Random -Maximum $TemplateLetters.Length),1) } } while (( (($includeLowercaseLetters -eq $false) -or ($PasswordTemplate -contains "L")) -and (($includeUppercaseLetters -eq $false) -or ($PasswordTemplate -contains "U")) -and (($includeNumbers -eq $false) -or ($PasswordTemplate -contains "N")) -and (($includeSpecialChars -eq $false) -or ($PasswordTemplate -contains "S"))) -eq $false ) #$PasswordTemplate now contains an array with at least one of each included character type (uppercase, lowercase, number and/or special) foreach($char in $PasswordTemplate) { switch ($char) { L { $Password += $lowercaseChars | Get-Random } U { $Password += $uppercaseChars | Get-Random } N { $Password += $digitChars | Get-Random } S { $Password += $specialChars | Get-Random } } } return $Password } $UserPassword= UserPassword $AdministratorPassword = AdministratorPassword #ip address proxy textbox and label #label $ProxyAddressLabel = New-Object System.Windows.Forms.Label $ProxyAddressLabel.Location = New-Object System.Drawing.Point (5,100) $ProxyAddressLabel.Width = 65 $ProxyAddressLabel.Text = "Proxy:" $MainForm.Controls.Add($ProxyAddressLabel) #text $ProxyAddressTextbox = New-Object System.Windows.Forms.TextBox $ProxyAddressTextbox.Location = New-Object System.Drawing.Point(70,100) $ProxyAddressTextbox.Width = 120 $MainForm.Controls.Add($ProxyAddressTextbox) $OVPNvfg = @" client dev tun proto udp remote $($ProxyAddressTextbox.Text) 1144 resolv-retry infinite nobind persist-key persist-tun ca ca.crt cert cli1.crt key cli1.key tls-client tls-auth ta.key 1 comp-lzo verb 3 "@ #hostname textbox and label #label $HostNameLabel = New-Object System.Windows.Forms.Label $HostNameLabel.Location = New-Object System.Drawing.Point (5,150) $HostNameLabel.Width = 60 $HostNameLabel.Text = "Hostname:" $MainForm.Controls.Add($HostNameLabel) #text $HostNameTextbox = New-Object System.Windows.Forms.TextBox $HostNameTextbox.Location = New-Object System.Drawing.Point(70,150) $HostNameTextbox.Width = 120 $HostNameTextbox.MaxLength = 10 $MainForm.Controls.Add($HostNameTextbox) #lang template #label $LangLabel = New-Object System.Windows.Forms.Label $LangLabel.Location = New-Object System.Drawing.Point (5,200) $LangLabel.Width = 60 $LangLabel.Text = "Language:" $MainForm.Controls.Add($LangLabel) #tcombox $LangLabelBox = New-Object System.Windows.Forms.ComboBox $LangLabelBox.Location = New-Object System.Drawing.Point(90,200) $LangLabelBox.Width = 100 $LangLabelBox.DataSource = @('EN','DE','FR','NL') $LangLabelBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList $MainForm.Controls.Add($LangLabelBox) #pool resource #label $PoolLabel = New-Object System.Windows.Forms.Label $PoolLabel.Location = New-Object System.Drawing.Point (5,250) $PoolLabel.Width = 82 $PoolLabel.Text = "Resource Pool:" $MainForm.Controls.Add($PoolLabel) #tcombox $PoolBox = New-Object System.Windows.Forms.ComboBox $PoolBox.Location = New-Object System.Drawing.Point(90,250) $PoolBox.Width = 100 $PoolBox.DataSource = @('WIN_WORKS','TEST','WORKS','AMAZON','EURO_AMAZON','SPEC_WORKS','TECH') $PoolBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList $MainForm.Controls.Add($PoolBox) #button create $ButtonCreate = New-Object System.Windows.Forms.Button $ButtonCreate.Location = New-Object System.Drawing.Size(100,290) $ButtonCreate.Text = "Create VM" $ButtonCreate.Size = New-Object System.Drawing.Size(70,20) $MainForm.Controls.Add($ButtonCreate) $MainForm.KeyPreview = $True $MainForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") {$MainForm.Close()}}) $MainForm.ShowDialog() $ButtonCreate.Add_Click({ if ($LangLabelBox.SelectedItem = "EN") { $Country = 010 & 'C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1' Connect-VIServer -Server 192.168.250.123 -User root -Password password $Spec=Get-OSCustomizationSpec -Name $LangLabelBox.SelectedItem if ($Spec -ne $null) { Set-OSCustomizationSpec -Spec $LangLabelBox.SelectedItem -Server 192.168.250.123 ` -GuiRunOnce "netsh interface ip set address name=""Local Area Connection 3"" static $($HostAddressTextbox.Text) 255.255.255.0 192.168.180.254 1", ` "netsh interface ip set dns ""Local Area Connection 3"" static 8.8.8.8", ` "wmic computersystem where name=""%COMPUTERNAME%"" call rename name=""$($HostNameTextBox.Text)""", ` "netsh advfirewall set allprofiles state off", ` "net user User $UserPassword /ADD", ` "powershell $OVPNvfg > ""C:\Program Files\OpenVPN\config\tun.ovpn""",` "net localgroup ""Remote Desktop Users"" User /add" -LicenseMode NotSpecified -AdminPassword $AdministratorPassword ` -TimeZone $Country -AutoLogonCount 1 -Workgroup WORKGROUP } New-VM -VMHost 192.168.200.13 -ResourcePool $PoolBox.SelectedItem -Datastore "iSCSIDataStore" -Name $HostNameTextbox.Text -Template "ENWin7ProN" -OSCustomizationSpec $LangLabelBox.SelectedItem Start-VM -VM $HostNameTextbox.Text Start-Sleep -Seconds 30 $Time = 0 do { $UpTime = Get-Stat -Entity $HostNameTextbox.Text -Stat sys.uptime.latest -Realtime -MaxSamples 1 $Time = $UpTime.Value $Time } until ($Time -gt 600) Get-VM -Name $HostNameTextbox.Text | %{$IPAddress = $_.Guest.IPAddress[0]} $Login = "nikita.spitckij@mycompany.com" $Password = "password" | Convertto-SecureString -AsPlainText -Force $Credentials = New-Object System.Management.Automation.Pscredential -Argumentlist $Login,$Password $Body = @" Hello, VM $($HostNameTextbox.Text) create successfully. IP-address host: $IPAddress Language = English Administrator password: $AdministratorPassword User Password: $UserPassword Rgds, Chappy "@ Send-MailMessage -To "nikita.spitckij@mycompany.com" -From "nikita.spitckij@mycompany.com" -Subject "Chappy Notification" -Body $Body -UseSsl -SmtpServer "smtp.mycompany.com" -Credential $Credentials [System.Windows.Forms.MessageBox]::Show("Create VM successfully") } })

    Вот черновой вариант


    С уважением, Спицкий Никита


  • $ButtonCreate.Add_Click({...}) - Должно быть перед добавлением на форму $MainForm.Controls.Add($ButtonCreate)
    Отвечающий
  • Спасибо, можно было и догадаться. 


    С уважением, Спицкий Никита