我想确定来自多个域的所有用户,其中密码到期日期与当前日期之间的差异小于 14 天。后来我想用powershell给所有用户写一封通知邮件。如何将姓氏内容写入变量? 这是我给定的代码:
$datacoll =@()
$domains = "domain1","domain2","domain3"
$expindays = 14
$today = Get-Date
foreach($domain in $domains){
$datacoll += Get-ADUser -Server $domain -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} `
–Properties “SamAccountName”,”mail”,"GivenName","Surname",”pwdLastSet”,”msDS-UserPasswordExpiryTimeComputed” | where{$_.mail -ne $null} |
Select-Object -Property “SamAccountName”,”mail”,"GivenName","Surname",@{Name=”Password Last Set”;`
Expression={[datetime]::FromFileTime($_.”pwdLastSet”)}}, @{Name=”Password Expiry Date”;`
Expression={[datetime]::FromFileTime($_.”msDS-UserPasswordExpiryTimeComputed”)}}
}
#iterate surname?
# foreach($user in $Surname){
# }
#datacoll output
$datacoll | Export-Csv "C:\pw.csv" -NoTypeInformation -Encoding utf8
最佳答案
您可以使用DirectoryServices和DirectoryServices.AccountManagement,它们是.NET框架的一部分
您可以使用 system.reflection.assemble 加载 .Net 程序集
[system.reflection.assembly]::LoadWithPartialName("System.DirectoryServices") | out-null
然后,您将创建一个域上下文(与 AD 的连接)和一个搜索器对象,该搜索器对象将在域中查找用户对象。
我编写了一个函数来返回与范围(距离到期日期有多近)和域匹配的用户。然后它将返回一个目录条目数组,以便您可以获得您喜欢的信息。
function Get-ADPasswordExpirationDates(){
param(
[Parameter(Mandatory=$True)]
[string]$Domain,
[int]$Range = 14
)
#Call .Net Active Directory Assembies
[system.reflection.assembly]::LoadWithPartialName("System.DirectoryServices") | out-null
[system.reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") | out-null
#Get Domain Context
$Context = new-object System.DirectoryServices.AccountManagement.PrincipalContext(`
[System.DirectoryServices.AccountManagement.ContextType]::Domain,`
$domain
)
#Create Searcher Object looking for User Objects
$Search = new-object System.DirectoryServices.AccountManagement.PrincipalSearcher(`
new-object System.DirectoryServices.AccountManagement.UserPrincipal(`
$Context
)
)
#Arry Varable for holding return reply
$Reply = @()
#For Each User in search
foreach($Result in $Search.FindAll()){
#Turn Result into a Directory Entry
[System.DirectoryServices.DirectoryEntry] $Entry = $Result.GetUnderlyingObject()
#Get Expiration Date
$Expiration = $Entry.InvokeGet("PasswordExpirationDate")
#Create a Timespan from Todays date to Expiration date
$Timespan = $(New-TimeSpan -Start $(get-date) -End $Expiration).Days
#If days are less then $RANGE add Directory Entry to array
if($Timespan -lt $Range -and $Timespan -gt -1 ){
$Reply += $Entry
}
}
return $Reply
}
以下是如何使用它从目录对象获取信息的快速示例。
$AlmostExpiredUsers = Get-ADPasswordExpirationDates -domain MyAwesomeDomainName -Range 14
foreach($User in $AlmostExpiredUsers){
Write-Output "Username : $($user.SamAccountName)`r`nFull Name : $($user.Properties.name)`r`nEmail : $($user.Properties.mail)`r`nExpires : $($user.InvokeGet("PasswordExpirationDate"))`r`n`r`n"
}
关于powershell - 今天的日期和密码的到期日期少于 14 天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50989367/