Reputation: 131
I have a bit of powershell that im running on the click of a button to create an AD group with the name provided in the textbox. The true statement works but the false statment does not execute. My code is below:
function Button_Click( )
{
$Nameofgroup = $TextBox1.text
if (Get-adgroup $nameofgroup)
{
[System.Windows.Forms.MessageBox]::Show(" $nameofgroup Already exists", "Alert")
}
else
{
[System.Windows.Forms.MessageBox]::Show(" $nameofgroup Created", "Alert")
NEW-ADGroup –name $Nameofgroup –groupscope Global –path “OU=example,OU=example,DC=Example,DC=example,DC=example”
}
If you would like to test this without using GUI you can use the below code instead.
$Nameofgroup = $TextBox1.text
if (Get-adgroup $nameofgroup)
{
Write-host "Already Exists"
}
else
{
Write-Host "Created Successfully"
NEW-ADGroup –name $Nameofgroup –groupscope Global –path “OU=example,OU=example,DC=Example,DC=example,DC=example”
}
If you test the AD group creation code on it's own this works fine.
Please let me know if you have any ideas on how to fix this.
Thanks,
SG
Upvotes: 0
Views: 357
Reputation: 1446
The Get-ADGroup cmdlet throws an exception if the group you specify doesn't exist. You could use a try catch statement to catch the exception but in my opinion it would just be easier to use the filter parameter to specify the group name (which will not produce an exception if your filter produces no results):
if (Get-ADGroup -Filter { Name -eq $nameofgroup })
{
[System.Windows.Forms.MessageBox]::Show(" $nameofgroup Already exists", "Alert")
}
else
{
[System.Windows.Forms.MessageBox]::Show(" $nameofgroup Created", "Alert")
New-ADGroup –name $Nameofgroup –groupscope Global –path "OU=example,OU=example,DC=Example,DC=example,DC=example"
}
With this code, if the group does not exist no error is produced (just a null response) and your else code should run.
Upvotes: 3