检查OU是否存在不正常

时间:2015-09-15 08:33:00

标签: powershell active-directory

编写这个小脚本来测试OU是否存在,如果存在写入控制台并终止。如果不存在则创建OU并执行其他一些操作。虽然似乎无法理解为什么我无法让它发挥作用。

由于某种原因,输出将始终告诉我OU存在,我很确定它不存在。我做错了什么?

这是代码:

param (
    [parameter(mandatory=$true)] [string] $servername
)

Import-Module ActiveDirectory

Function CheckOU {
    $script:OUpath = "OU=$servername,OU=Rechtengroepen,OU=danny,dc=Doenoe,DC=com"
    $Status = $false
    $GetOU = Get-ADOrganizationalUnit -Identity $OUpath -ErrorAction SilentlyContinue

    if ($GetOU -eq $null) {
        $status = $false
        Write-Host -ForegroundColor Green "$OUpath does not exist." 
    } else {
        $Status = $true
        Write-Host -ForegroundColor Red "$OUpath exists!"
    }
    return $Status
}

$OUStatus = CheckOU

if ($OUStatus -eq $true) {
    Write-Host "$OUpath exists. Function working."
} else {
    Write-Host "$OUpath does not exsist, do something."
}

输出:

Get-ADOrganizationalUnit : Directory object not found
At C:\Scripts\CreateOUgroups\createadgroups_test02.ps1:10 char:14
+     $GetOU = Get-ADOrganizationalUnit -Identity $OUpath -ErrorAction SilentlyCon ...
+              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (OU=notexistsing...c=Doenoe,DC=com:ADOrganizationalUnit) [Get-ADOrganizationalUnit], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADOrganizationalUnit

OU=notexistsingOU,OU=Rechtengroepen,OU=danny,dc=Doenoe,DC=com exists!
OU=notexistsingOU,OU=Rechtengroepen,OU=danny,dc=Doenoe,DC=com exists. Function working.

1 个答案:

答案 0 :(得分:4)

如果具有给定标识的对象不存在,则将cmdlet与-Identity参数一起使用会导致终止错误。使用-Filter可以避免此问题:

Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$OUPath'"