简体   繁体   中英

Powershell script to check if ADGroup exist if not add to custom object

Hi I'm trying to create a script that will check if the list of AD Group I provided exist in AD but the script only returns the last object it found. Please disregard the previous sample code and refer to this one. The script seems to run but it is not returning all the ADGroup in the list even if they all exist as confirmed manually. It only returns the last object.

       function CheckAD

{


$AD= "AA","BB"

foreach ($group in $AD)
{

$R_AD= @()

$R_AD=Get-ADGroup -filter {GroupCategory -eq "Security" -and Name -eq $group} -SearchBase "OU=Application,OU=SOO,OU=Groups,OU=UN,DC=B3,DC=in"|select -ExpandProperty     name -Unique

if ($R_AD.count -gt 0)
{
$r = New-Object -TypeName psobject
$r|Add-Member -MemberType NoteProperty -Name ADGroup -Value $R_AD
}

} 

return($r)

}

$Test=CheckAD
## Cleaned-up the formatting so I could read this
function CheckAD {
    ## Changed to a hash table; consider passing 
    ## these in as parameters
    $AD = @{"AA" = $false; "BB" = $false}

    foreach ($group in $AD.keys) {
        ## You don't need this. Removing.
        #$R_AD = @()

        ## In your post, you asked to know if the group existed.
        if ( $(Get-ADGroup -filter {GroupCategory -eq "Security" -and Name -eq $group} -SearchBase "OU=Application,OU=SOO,OU=Groups,OU=UN,DC=B3,DC=in") ) {
            $AD[$group] = $true 
        }

        ## You don't need this either
        #if ($R_AD.count -gt 0) {
        #    $r = New-Object -TypeName psobject
        #    $r|Add-Member -MemberType NoteProperty -Name ADGroup -Value $R_AD
        #}

    } 

    #return($r)
    return($AD)

}

$Test = CheckAD

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