Powershell Add_Click代码只写主机工作

时间:2016-02-11 16:30:22

标签: forms powershell

[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

当我把" Get-Mailbox -Identity $ acns"在脚本的最后它按预期工作。但是当我放入add_click

时却没有

1 个答案:

答案 0 :(得分:0)

GUI应用程序没有控制台,因此通常的“将每个未保存的对象抛出到控制台”都不适用。您需要指定它应该与ex一起进入控制台。 Out-DefaultOut-Host(Out-Default发送给),或转换为字符串并显示,例如

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

请记住:命令仍然可以工作,对象可以通过管道输送到Set-Mailbox等。这只是需要特别注意的控制台输出。我建议使用GUI进行用户输出或完全跳过GUI /单击关闭它,让控制台显示其余部分。混合只是混乱。