简体   繁体   中英

Powershell Add_Click code only write-host working

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Mailbox Creation Wizard"
$objForm.Size = New-Object System.Drawing.Size(380,230) 
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True

#Mailbox new user check
$UserButton = New-Object System.Windows.Forms.Button
$UserButton.Location = New-Object System.Drawing.Size(160,70)
$UserButton.Size = New-Object System.Drawing.Size(150,23)
$UserButton.Text = "Check new user"
$UserButton.Add_Click({
    $global:acns = [Microsoft.VisualBasic.Interaction]::InputBox("Enter account name", "Finalise new account", "atsi")
    if ($acns) { 
        #the get-mailbox query does not work if it get's valid output. if for example i put a query with no result or no valid results i get an error message.
        Get-Mailbox -Identity "$acns" 
    }
        else {
        Write-Host "No input given" 
        }
    })
#    else { Write-Host "$acns" }})
$objForm.Controls.Add($UserButton)

#Cancel button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(10,160)
$CancelButton.Size = New-Object System.Drawing.Size(150,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

[void] $objForm.ShowDialog()

write-host $acns

When I put "Get-Mailbox -Identity $acns" at the end of the script it works as intended. but not when I put in the add_click

GUI applications doesn't have a console, so the usual "throw every non-saved object to the console" doesn't apply. You need to specify that it should go the the console with ex. Out-Default , Out-Host (which Out-Default sends to), or convert to string and show that, ex.

Get-Mailbox -Identity "$acns" | Out-Default
Get-Mailbox -Identity "$acns" | Out-Host
#Since you're still in the GUI-application you won't be able to use the output anyways, so you might as well print it as a string
Get-Mailbox -Identity "$acns" | Out-String | Write-Host

Remember: The commands still work and objects can be piped to Set-Mailbox etc. It's just the console output that need special attention. I would recommend using the GUI for user output or skip the GUI completely/close it on click and let the console show the rest. Mixing is just messy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM