2016-11-16 89 views
0

我正在使用UserPrincipal收集非域成員服務器上本地用戶的詳細信息。我想在密碼過期或過期時向用戶發送電子郵件。POWERSHELL:使用UserPrincipal獲取密碼過期日期

我擁有除最大密碼年齡以外的所有內容。我無法獲得這個價值,我發現所有我認爲不需要的有關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 

我敢肯定它的簡單,我忽略東西明顯....

回答

0

您可能沒有得到一個值,因爲本地用戶帳戶的密碼到期沒有啓用默認情況下。

您需要在計算機本地安全策略中手動啓用Maximum password age


編輯:可以讀取本地安全策略從註冊表中的值設置:

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

這將是有意義的代碼明智的,但我們的用戶帳戶會過期,需要密碼被改變。 – neildeadman

+0

查看更新回答 –

+0

這似乎工作,只是測試,並會回覆給你。謝謝。 – neildeadman