我的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()
问候,
拉尔夫
最佳答案
Enable-ADAccount
默认不返回任何输出,因此整个管道表达式为:
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount
...将不会有任何结果-在您的
$false
条件下,所有这些都不会影响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.")
}
或者将
-PassThru
开关与Enable-ADAccount
一起使用,以使其返回帐户,然后检查:$enabledAccount = Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -PassThru
if($enabledAccount.Enabled){
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
关于powershell - Powershell if else语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60837696/