编写这个小脚本来测试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:ScriptsCreateOUgroupscreateadgroups_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.
如果具有给定标识的对象不存在,则使用带有-Identity
参数的cmdlet会导致终止错误。使用-Filter
来避免这个问题:
Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$OUPath'"