POWERSHELL:使用UserPrincipal获取密码到期日期

时间:2016-11-16 17:24:56

标签: powershell

我使用UserPrincipal收集非域成员服务器上的本地用户的详细信息。我希望在密码过期或过期时向用户发送电子邮件。

我拥有除Max Password Age之外的所有东西。我无法获得这个价值,而且我发现的所有内容都与我不需要的Active Directory连接有关。当我尝试将其调整到本地服务器时,它无法正常工作。

这就是我所拥有的:

$date = Get-Date
$contextType = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($contextType)
$principalSearcher = New-Object System.DirectoryServices.AccountManagement.PrincipalSearcher(New-Object System.DirectoryServices.AccountManagement.UserPrincipal($principalContext))

ForEach($userPrincipal in $principalSearcher.FindAll())
{
    $maxPasswordAge = 90

    $name = $userPrincipal.Name
    $samAccountName = $userPrincipal.SamAccountName
    $description = $userPrincipal.Description
    $fullname = $userPrincipal.DisplayName
    $lastPasswordSet = $userPrincipal.LastPasswordSet
    $passwordExpires = $lastPasswordSet.AddDays($maxPasswordAge)
    $passwordExpiresDays = New-TimeSpan -Start $date -End $passwordExpires
    $passwordExpiresDays = [Math]::Floor($passwordExpiresDays.TotalDays)

    Write-Host "Name: "$name
    Write-Host "SAM Account Name: "$samAccountName
    Write-Host "Full Name: "$fullName
    Write-Host "Password last set: "$lastPasswordSet
    Write-Host "Password expires: "$passwordExpiresDays
    Write-Host "Max Password Age: "$maxPasswordAge
}

在上面的代码中,我手动将值设置为90以使我的代码正常工作。我需要用代码替换它以检索正确的值。

我尝试过以下操作从UserPrincipal中提取DirectoryEntry对象,然后是本机对象,但我无法让它工作:

$directoryEntry = $userPrincipal.GetUnderlyingObject()
$native = [ADSI]$directoryEntry.NativeObject

我确信这很容易,而且我忽略了一些显而易见的事情......

1 个答案:

答案 0 :(得分:0)

您可能没有获得值,因为默认情况下未启用本地用户帐户的密码过期。

您需要在计算机本地安全策略中手动启用Maximum password age

编辑:您可以从注册表中读取本地安全策略设置的值:

$maxPasswordAge = (Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters -Name MaximumPasswordAge).MaximumPasswordAge