我有一个脚本,它将收集 2018 年 1 月之前未登录的用户列表并以单个 CSV 格式输出。
我需要的输出类似于 OU1 用户输出到 ou1.csv,ou2 用户输出到 OU2.csv。
下面是我的脚本。
$Today = (get-date -f MM-dd-yyyy)
$OUs = (Get-Content E:\DATA\Password lastset before jan 2018\OU.txt)
foreach ($OU in $OUs)
{
Get-ADUser -filter {Enabled -eq $true} -SearchBase $OUs -Properties DisplayName,SamAccountName,distinguishedname,cn,PasswordNeverExpires,passwordlastset,LastLogonDate,EmailAddress |
where{ $_.PasswordNeverExpires -eq $false } | where{$_.passwordlastset -le ((get-date).adddays(-90))} |
Where{ $_.LastLogonDate -le ((get-date).adddays(-240))} |
select samaccountname, Displayname,
@{n='ParentContainer';e={$_.distinguishedname -replace '^.+?,(CN|OU.+)','$1'}},@{Name="PasswordAge";`
Expression={((Get-Date)-$_.PasswordLastSet).days}}, @{N="LastLogonDate";E={$_.LastLogonDate}},@{n="EmailAddress";E={$_.EmailAddress}} |
Export-CSV "E:\DATA\PasswordPolicy\ADUser lastlogon on or before Jan 2018 report-$Today.csv" -NoTypeInformation -Encoding UTF8
}
$Body = "ADUser lastlogon before Jan 2018"
Send-mailmessage -to "[email protected]" -from [email protected] -SmtpServer usvasmtp -Body $Body -subject "OU1 ADUser lastlogon on or before Jan 2018 - Report For $Today" -Attachments "E:\DATA\PasswordPolicyEmail\OU1-$Today.csv"
Send-mailmessage -to "[email protected]" -from [email protected] -SmtpServer usvasmtp -Body $Body -subject "OU2 ADUser lastlogon on or before Jan 2018 - Report For $Today" -Attachments "E:\DATA\PasswordPolicyEmail\OU2-$Today.csv"
答案1
代替:
Export-CSV "E:\DATA\PasswordPolicy\ADUser lastlogon on or before Jan 2018 report-$Today.csv" -NoTypeInformation -Encoding UTF8
和:
Export-CSV $path -NoTypeInformation -Encoding UTF8
添加:
$path = "E:\DATA\PasswordPolicy\" + $ou + ".csv"
在 foreach 循环的状态
如果你在 OU.txt 中指定完整的 DN,那么你$($ou.split("ou=")[-1])
也可以使用类似的方法修复你的 Searchbase:-SearchBase $OU