简体   繁体   中英

Powershell Gui If Statement not working

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

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.

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