【问题标题】:Powershell LDAP Filter with DirectorySearcher带有 DirectorySearcher 的 Powershell LDAP 过滤器
【发布时间】:2019-02-06 04:09:43
【问题描述】:

我正在使用DirectorySearcher 类来查找单个用户。条件应该是objectCategory 是用户,并且他的密码未设置为永不过期。

经过一番搜索,我想出了这个:

$searcher = New-Object System.DirectoryServices.DirectorySearcher

$searcher.Filter = "(&(objectCategory=User)(samAccountName=$env:username)(!(userAccountControl:1.2.840.113556.1.4.803:=65536)))"

userAccountControl:1.2.840.113556.1.4.803:=65536 应该用于密码永不过期的用户。

我终于做到了:

$user = $searcher.FindOne().GetDirectoryEntry()

但它说我不能在空值表达式上调用方法。我想我正确地使用了括号。那么可能是我不能使用!运算符?

另外请注意,我可以使用get-aduser 命令,如下所示:

get-aduser -filter * -properties samAccountName, PasswordNeverExpires | where { $_.passwordNeverExpires -eq "true" } | where {$_.enabled -eq "true"} | where {$_.samAccountName -eq $env:username}

但在这种情况下,最好使用DirectorySearcher,而不是如上所示。

【问题讨论】:

  • 您的搜索在我的电脑上运行良好(Windows 7:PS 5.0)
  • @JPBlanc 我有 PSVersion 3.0,它是旧服务器
  • 请问您为什么不想使用Get-ADUser cmdlet?

标签: powershell active-directory ldap


【解决方案1】:

实际上你的代码是可以工作的,但是当$searcher.FindOne() 什么都不返回,也就是说,当过滤器什么都不返回时,GetDirectoryEntry() 方法给出:

> You cannot call a method on a null-valued expression. At line:1 char:1
> + $searcher.FindOne().GetDirectoryEntry()
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>     + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
>     + FullyQualifiedErrorId : InvokeMethodOnNull

试试看:

$user = $searcher.FindOne()
if($user -ne $null) {$user.GetDirectoryEntry()} else {write-host "Niet"}

【讨论】:

  • 两次调用.FindOne() 本身就是一种浪费。 $user = $searcher.FindOne(); if ($user) { $user.GetDirectoryEntry() } else { Write-Host "Niet" }
  • @Tomalak 你完全正确。我以这种方式编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多