gpt4 book ai didi

powershell - 检查OU是否存在无法正常工作

转载 作者:行者123 更新时间:2023-12-03 00:49:41 26 4
gpt4 key购买 nike

编写此小脚本以测试OU是否存在,是否存在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.

最佳答案

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

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

关于powershell - 检查OU是否存在无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32581359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com