简体   繁体   English

Powershell 获取计算机 AD OU 并与定义的字符串进行比较

[英]Powershell Get computer AD OU and compare to defined string

I am in need to get the AD OU computer belongs to and compare to specified string.我需要获取属于指定字符串的 AD OU 计算机并进行比较。 I will be running the script on the pc itself with some machines running Windows 7 Embedded with Powershell v2.我将使用一些运行 Windows 7 Embedded with Powershell v2 的机器在 PC 上运行脚本。

I have tried the script on Windows 10 and its working fine.我已经在 Windows 10 上尝试过这个脚本并且它工作正常。 However, I get this error on the Embedded pc with powershell v2:但是,我在带有 powershell v2 的嵌入式 PC 上收到此错误:

Method invocation failed because [System.DirectoryServices.PropertyValueCollection] doesn't contain a method named 'Split'.方法调用失败,因为 [System.DirectoryServices.PropertyValueCollection] 不包含名为“Split”的方法。

    $ComputerName = $env:computername
    $Filter = "(&(objectCategory=Computer)(Name=$ComputerName))"

    $DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
    $DirectorySearcher.Filter = $Filter
    $SearcherPath = $DirectorySearcher.FindOne()
    $DistinguishedName = $SearcherPath.GetDirectoryEntry().DistinguishedName

    $OUName = ($DistinguishedName.Split(","))[1]
    $OUMainName = $OUName.SubString($OUName.IndexOf("=")+1)

# Compare OU name to specified string
If ($OUMainName -eq "BT")
    {
        $PreferredServer=$BTServer
        $AlternativeServer=$TTServer

Any help will be appreciated.任何帮助将不胜感激。 I am pretty new to powershell.我对powershell很陌生。 Thanks.谢谢。

So the line...所以线...

$DistinguishedName = $SearcherPath.GetDirectoryEntry().DistinguishedName

is returning an object of the type...正在返回类型的对象...

[System.DirectoryServices.PropertyValueCollection]

And that object type does not support the split method.并且该对象类型不支持 split 方法。 I think you are probably interested in the stringified output from the AD object so you just need to convert the name property into a string before splitting, either at time of storage into the variable or at time where the split takes place like this...我认为您可能对来自 AD 对象的字符串化输出感兴趣,因此您只需要在拆分之前将 name 属性转换为字符串,无论是在存储到变量时还是在拆分发生时,像这样......

At variable storage在变量存储

$DistinguishedName = ($SearcherPath.GetDirectoryEntry().DistinguishedName).tostring()

At Split invocation在拆分调用时

$OUName = ($DistinguishedName.tostring().Split(","))[1]

That said, I'm not quite sure if you are only getting to the PropertyValueCollection object that you won't need to additionally select the specific Value property of the target Property (OU or path probably?) before you can convert it into a string.也就是说,我不太确定您是否只访问 PropertyValueCollection 对象,在将其转换为字符串之前,您不需要额外选择目标属性的特定 Value 属性(可能是 OU 或路径?) .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM