Powershell - 清除后无法检索活动目录属性

时间:2014-11-20 06:13:26

标签: powershell active-directory

我正在清除计算机的AD属性。 然后我尝试将该属性更改为某个值。但是,当我查看该AD对象的属性时,该属性似乎不再存在:

function clearAttribute
{
    $directorySearcher = New-Object System.DirectoryServices.DirectorySearcher
    $directorySearcher.PageSize = 100
    $directorySearcher.SearchScope = [System.DirectoryServices.SearchScope]::Subtree
    $directorySearcher.Filter = "(&(objectCategory=computer)(cn=computerName1))"
    $result = $directorySearcher.FindOne()
    if ($result.Properties.Contains("netbootmachinefilepath"))
    {
        $directoryEntry = $result.GetDirectoryEntry()
        $directoryEntry.Properties["netbootmachinefilepath"].Clear()
        $directoryEntry.CommitChanges()
    }
}

function setAttribute
{
    $directorySearcher = New-Object System.DirectoryServices.DirectorySearcher
    $directorySearcher.PageSize = 100
    $directorySearcher.SearchScope = [System.DirectoryServices.SearchScope]::Subtree
    $directorySearcher.Filter = "(&(objectCategory=computer)(cn=computerName1))"
    $result = $directorySearcher.FindOne()
    if ($result.Properties.Contains("netbootmachinefilepath")) ###THIS IS FALSE!###
    {
        $directoryEntry = $result.GetDirectoryEntry()
        $directoryEntry.Properties["netbootmachinefilepath"].Value = "someValue"
        $directoryEntry.CommitChanges()
    }
}
clearAttribute
setAttribute

编辑:结果显示此属性可以是非空白或已删除(它不能为空)。在"清除"它,如果你想更新它,它将不得不重新创建。

1 个答案:

答案 0 :(得分:0)

原来我错误地认为如果$ result.Properties.Contains(“netbootmachinefilepath”)= FALSE则无法设置属性的值。 不是这种情况。 $ result.Properties.Contains(“netbootmachinefilepath”)= FALSE只是意味着该值为null(或者也可能是该属性不存在?)。

如果你只是删除if语句,如下所示,代码可以工作:

function setAttribute
{
    $directorySearcher = New-Object System.DirectoryServices.DirectorySearcher
    $directorySearcher.PageSize = 100
    $directorySearcher.SearchScope = [System.DirectoryServices.SearchScope]::Subtree
    $directorySearcher.Filter = "(&(objectCategory=computer)(cn=computerName1))"
    $result = $directorySearcher.FindOne()

    $directoryEntry = $result.GetDirectoryEntry()
    $directoryEntry.Properties["netbootmachinefilepath"].Value = "someValue"
    $directoryEntry.CommitChanges()
}