Powershell 检查 OU 是否存在

发布于 2024-11-26 05:02:56 字数 684 浏览 0 评论 0原文

我试图在创建 OU 之前检查它是否存在。我的问题是,我有 2 个母 OU“USER BY SITE”和“GROUP BY SITE”,并且我需要在这 2 个中拥有完全相同的 OU,其中 1 个用于存储用户,另一个用于存储组。

到目前为止我使用了这个函数:

function CheckOUExist
{
    param($OUToSeek)

    $LDAPPath = "LDAP://dc=Domain,dc=local"

    $seek = [System.DirectoryServices.DirectorySearcher]$LDAPPath
    $seek.Filter = “(&(name=$OUToSeek)(objectCategory=organizationalunit))”
    $Result = $seek.FindOne()

    return $Result
}

有一个问题,即使$LDAPPath =“OU=USERS BY SITE,DC=Domain,DC=local”,我总是得到“GROUP BY SITE”中存在的OU。我在那里错过了什么吗?有没有办法让 [System.DirectoryServices.DirectorySearcher] 仅在我在 $LDAPPath 中给出的 OU 中工作?

如果您需要更准确的详细信息,我很乐意提供。

先感谢您。

I'm trying to check if an OU exist before creating it. My problem is that I have 2 mother OU "USER BY SITE" and "GROUP BY SITE", and I need to have the exact same OU in those 2, 1 for storing users, the other for storing groups.

So far I used this function :

function CheckOUExist
{
    param($OUToSeek)

    $LDAPPath = "LDAP://dc=Domain,dc=local"

    $seek = [System.DirectoryServices.DirectorySearcher]$LDAPPath
    $seek.Filter = “(&(name=$OUToSeek)(objectCategory=organizationalunit))”
    $Result = $seek.FindOne()

    return $Result
}

There is my problem, I always get the OU existing in "GROUP BY SITE" even if $LDAPPath = "OU=USERS BY SITE,DC=Domain,DC=local". Am I missing something there? Is there a way to for the [System.DirectoryServices.DirectorySearcher] to work only in the OU I gived in the $LDAPPath?

If you need more accurate detail, I'll gladly provide them.

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

ˇ宁静的妩媚 2024-12-03 05:02:56

尝试 Exists 方法,您分别返回 true/false:

[adsi]::Exists("LDAP://OU=test,DC=domain,DC=com")

Try the Exists method, you get back true/false respectively:

[adsi]::Exists("LDAP://OU=test,DC=domain,DC=com")
土豪 2024-12-03 05:02:56

如果您使用干净的数据,那么按照 Shay 的建议,以下内容非常有效。

[string] $Path = 'OU=test,DC=domain,DC=com'
[adsi]::Exists("LDAP://$Path")

感谢这个伟大的起点!但是,如果您正在验证可能不干净的数据,则会抛出错误。可能错误的一些示例是:

  • 如果某些内容的格式不正确
    • (错误:指定了无效的 dn 语法)
  • 如果域不存在
    • (错误:服务器无法运行)
  • 如果域无法与您通信
    • (错误:从服务器返回引用)

所有这些错误都应使用 [System.Management.Automation.RuntimeException] 捕获,或者您可以将 catch 语句留空以捕获全部。

简单示例:

[string] $Path = 'OU=test,DC=domain,DC=com'
try {
    $ou_exists = [adsi]::Exists("LDAP://$Path")
} catch {
    # If invalid format, error is thrown.
    Throw("Supplied Path is invalid.`n$_")
}

if (-not $ou_exists) {
    Throw('Supplied Path does not exist.')
} else {
    Write-Debug "Path Exists:  $Path"
}

更多详细信息:
http://go.vertigion.com/PowerShell-CheckingOUExists

The following, as suggested by Shay, works great if you're working with clean data.

[string] $Path = 'OU=test,DC=domain,DC=com'
[adsi]::Exists("LDAP://$Path")

Thanks for this great starting point! However, if you're verifying potentially unclean data, you'll get thrown an error. Some examples of possible errors are:

  • If the something isn't formatted properly
    • (ERR: An invalid dn syntax has been specified)
  • If the domain doesn't exist
    • (ERR: The server is not operational)
  • If the domain won't communicate with you
    • (ERR: A referral was returned from the server)

All of these errors should be caught with [System.Management.Automation.RuntimeException] or you can just leave the catch statement blank to catch all.

Quick Example:

[string] $Path = 'OU=test,DC=domain,DC=com'
try {
    $ou_exists = [adsi]::Exists("LDAP://$Path")
} catch {
    # If invalid format, error is thrown.
    Throw("Supplied Path is invalid.`n$_")
}

if (-not $ou_exists) {
    Throw('Supplied Path does not exist.')
} else {
    Write-Debug "Path Exists:  $Path"
}

More details:
http://go.vertigion.com/PowerShell-CheckingOUExists

任性一次 2024-12-03 05:02:56

问题在于 DirectorySearcher 对象的构造。要正确设置搜索根,需要使用 DirectoryEntry 对象([ADSI] 类型加速器)构造 DirectorySearcher,而您使用的是字符串。当使用字符串时,该字符串用作 LDAP 过滤器,并且搜索根为空,导致搜索器使用当前域的根。这就是为什么它看起来没有搜索您想要的 OU。

我想如果您执行如下操作,您将会得到您正在寻找的结果:

$searchroot = [adsi]"LDAP://OU=USERS BY SITE,DC=Domain,DC=local"

$seek = New-Object System.DirectoryServices.DirectorySearcher($searchroot)
$seek.Filter = "(&(name=$OUToSeek)(objectCategory=organizationalunit))"
... etc ...

请注意,首先构造了一个 DirectoryEntry,然后使用它来构造 DirectorySearcher。

The problem is the construction of the DirectorySearcher object. To properly set the search root, the DirectorySearcher needs to be constructed using a DirectoryEntry object ([ADSI] type accelerator), whereas you are using a string. When a string is used, the string is used as the LDAP filter and the search root is null, causing the searcher to use the root of the current domain. That is why it looks like it isn't searching the OU you want.

I think you will get the results you are looking for if you do something like the following:

$searchroot = [adsi]"LDAP://OU=USERS BY SITE,DC=Domain,DC=local"

$seek = New-Object System.DirectoryServices.DirectorySearcher($searchroot)
$seek.Filter = "(&(name=$OUToSeek)(objectCategory=organizationalunit))"
... etc ...

Notice that a DirectoryEntry is first constructed, which is then used to construct the DirectorySearcher.

春庭雪 2024-12-03 05:02:56

怎么样:

#Requires -Version 3.0

# Ensure the 'AD:' PSDrive is loaded.
if (-not (Get-PSDrive -Name 'AD' -ErrorAction Ignore)) {
    Import-Module ActiveDirectory -ErrorAction Stop
    if (-not (Get-PSDrive -Name 'AD' -ErrorAction Silent)) {
        Throw [System.Management.Automation.DriveNotFoundException] "$($Error[0]) You're likely using an older version of Windows ($([System.Environment]::OSVersion.Version)) where the 'AD:' PSDrive isn't supported."
    }
}

既然 AD: PSDrive 已加载,我们有几个选项:

$ou = "OU=Test,DC=Contoso,DC=com"
$adpath = "AD:\$ou"

# Check if this OU Exist
Test-Path $adpath

# Throw Error if OU doesn't exist
Join-Path 'AD:' $ou -Resolve

有关此主题的更多信息:玩转广告:驾驶乐趣和利润

How about:

#Requires -Version 3.0

# Ensure the 'AD:' PSDrive is loaded.
if (-not (Get-PSDrive -Name 'AD' -ErrorAction Ignore)) {
    Import-Module ActiveDirectory -ErrorAction Stop
    if (-not (Get-PSDrive -Name 'AD' -ErrorAction Silent)) {
        Throw [System.Management.Automation.DriveNotFoundException] "$($Error[0]) You're likely using an older version of Windows ($([System.Environment]::OSVersion.Version)) where the 'AD:' PSDrive isn't supported."
    }
}

Now that the AD: PSDrive is loaded, we have a couple of options:

$ou = "OU=Test,DC=Contoso,DC=com"
$adpath = "AD:\$ou"

# Check if this OU Exist
Test-Path $adpath

# Throw Error if OU doesn't exist
Join-Path 'AD:' $ou -Resolve

More info on this topic: Playing with the AD: Drive for Fun and Profit

白云悠悠 2024-12-03 05:02:56
Import-Module ActiveDirectory
Function CheckIfGroupExists{
    Param($Group)
    try{
        Get-ADGroup $Group
    }
    catch{
        New-ADGroup $Group -GroupScope Universal
    }
}

也会工作

Import-Module ActiveDirectory
Function CheckIfGroupExists{
    Param($Group)
    try{
        Get-ADGroup $Group
    }
    catch{
        New-ADGroup $Group -GroupScope Universal
    }
}

Will also work

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文