vendredi 19 août 2016

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

Aucun commentaire:

Enregistrer un commentaire