Powershell if else语句

问题描述 投票:0回答:1

我在Powershell脚本中遇到一些困难。使用此脚本,我可以启用禁用的AD帐户。它有效,但是我收到的输出错误。帐户已启用,但仍从else语句“尚未启用帐户”接收输出。有人可以帮助我吗?谢谢!

Add-Type -AssemblyName System.Windows.Forms

$SystemInfoForm = New-Object System.Windows.Forms.Form
$SystemInfoForm.ClientSize = "300,100"
$SystemInfoForm.Text = "Enable AD Accounts"
$SystemInfoForm.BackColor = "#ffffff"
$SystemInfoForm.StartPosition = "CenterScreen"

$objIcon = New-Object system.drawing.icon ("C:\Temp\System Info.ico")
$SystemInfoForm.Icon = $objIcon

$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Please enter the disabled AD account below:'
$SystemInfoForm.Controls.Add($label)

$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$textBox.Text = "Enter AD account..."
$SystemInfoForm.Controls.Add($textBox)

$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(10,70)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Add_Click(
    {
        $Username = $textBox.Text

        if (Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount)
        {
            [System.Windows.MessageBox]::Show("$Username has been enabled.")
        }
        else
        {
            [System.Windows.MessageBox]::Show("$Username has not been enabled.")
        }
    }
)

$SystemInfoForm.Controls.Add($okButton)

[void]$SystemInfoForm.ShowDialog()

关于,拉尔夫

powershell
1个回答
1
投票

Enable-ADAccount不返回任何输出,因此整个管道表达式:

Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount 

...将求和为nothing-并且在您的$false条件下所有nothing都将求值为if

使用try / catch块来捕获Enable-ADAccount中的错误,然后基于此警告警报:

try {
    Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -ErrorAction Stop

    # We got this far because Enable-ADAccount didn't throw any errors
    [System.Windows.MessageBox]::Show("$Username has been enabled.")
}
catch {
    [System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
© www.soinside.com 2019 - 2024. All rights reserved.