Powershell:如何查询 pwdLastSet 并使其有意义?

Bob*_*Bob 17 powershell active-directory

我需要为 Active Directory 安全组中的一组帐户获取最后一次密码更改,我觉得这是 PowerShell 应该擅长的。

现在,我已经被困在如何从我正在查看的 AD 帐户中读取 pwdLastSet 属性。甚至运行像这样简单的东西:

[adsi] "LDAP://cn=user1,ou=Staff,ou=User Accounts,dc=ramalamadingdong,dc=net" | Format-List *
Run Code Online (Sandbox Code Playgroud)

给出 pwdLastSet 的结果,如下所示:

pwdLastSet            : {System.__ComObject}
Run Code Online (Sandbox Code Playgroud)

我觉得我走错了路,那么查询和格式化 pwdLastSet 属性的输出(该值基于 Windows Epoch 并且不是很容易阅读)的最佳方法是什么?

Neo*_*yte 20

Windows 7/Windows Server 2008 R2 附带的内置 AD commandlet 现在可以非常简单地完成此操作。在 Windows 7 上通过 Powershell 提示:

Import-Module ActiveDirectory
Get-ADUser 'user1' -properties PasswordLastSet | Format-List
Run Code Online (Sandbox Code Playgroud)

“PasswordLastSet”属性似乎是实际“pwdLastSet”属性的翻译版本。


Bra*_*tch 14

您也可以在没有管理单元的情况下执行此操作。我试过了,它奏效了:

PS #> $searcher=New-Object DirectoryServices.DirectorySearcher
PS #> $searcher.Filter="(&(samaccountname=user1))"
PS #> $results=$searcher.findone()
PS #> [日期时间]::fromfiletime($results.properties.pwdlastset[0])

2009 年 6 月 10 日星期三下午 4:32:08

如果我有这样的用户对象设置,我也会得到一个 System.__ComObject for pwdLastSet:
$user = [adsi] "LDAP://cn=user1,ou=Staff,ou=User Accounts,dc=ramalamadingdong,dc=net ”

应该有一种方法可以使用 [System.__ComObject].InvokeMember() 和反射从 $user 对象中获取 pwdLastSet 值,但我一直没能把它弄对。我从来没有弄清楚,所以我使用了上面的例子并继续前进。

如果您要使用 AD(或 Exchange 或 SQL Server)进行大量工作,您可能需要为其获取管理单元并使用它。


Adi*_*bar 5

有一个更简单的方法。

ADSI 对象有一个名为 ConvertLargeIntegerToInt64 的方法。请注意,它是 ADSI 对象的方法,而不是通过查询时间戳属性的值返回的 System.__Comobject,因此 $user.pwdLastSet.value.ConvertLargeIntegerToInt64() 将不起作用。您需要按如下方式调用它:

$user.ConvertLargeIntegerToInt64($user.pwdLastSet.value)
Run Code Online (Sandbox Code Playgroud)

这将为您提供 LDAP 时间戳,需要将其转换为可读日期,如上面 Braatch 所解释的。这适用于 ADSI 提供程序返回的任何时间戳属性值,并且 ConvertLargeIntegerToInt64 方法(我相信)由表示目录条目的任何对象公开。

总而言之,以下是获取上次设置密码的日期的方法:

$user = [ADSI]'LDAP://cn=someusername,ou=someou,dc=somedomain,dc=com'
[datetime]::FromFileTime($user.ConvertLargeIntegerToInt64($user.pwdLastSet.value))
Run Code Online (Sandbox Code Playgroud)