简体   繁体   English

Powershell Gui If语句不起作用

[英]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. 我有一些功能强大,可以通过单击按钮来运行,以使用文本框中提供的名称创建一个AD组。 The true statement works but the false statment does not execute. true语句有效,但false语句不执行。 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. 如果要在不使用GUI的情况下进行测试,则可以改用以下代码。

$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. 如果自己测试AD组创建代码,则可以正常工作。

Please let me know if you have any ideas on how to fix this. 如果您对解决此问题有任何想法,请告诉我。

Thanks, 谢谢,

SG SG

The Get-ADGroup cmdlet throws an exception if the group you specify doesn't exist. 如果指定的组不存在,则Get-ADGroup cmdlet会引发异常。 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): 您可以使用try catch语句来捕获异常,但是我认为使用filter参数指定组名会更容易(如果您的过滤器未产生结果,则不会产生异常):

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. 使用此代码,如果该组不存在,则不会产生任何错误(只是一个空响应),您的else代码应运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM