[英]Powershell Active Directory script to export csv with specific information/attributes
[英]Powershell script check if user exists in Active Directory and export to csv
我有一个现有的脚本,它可以检查给定用户是否存在于 AD 中。 但我无法将结果导出到 csv 文件中。 请帮忙。
Clear-Host
$UserList = gc .\Output_userInfo.csv
$outputFilePath = "D:\Input\User&Group_Output.csv"
foreach ($u in $UserList) {
try {
$ADUser = Get-ADUser -Identity $u -ErrorAction Stop
}
catch {
if ($_ -like "Cannot find an object with identity: '$u'") {
"User '$u' does not exist." | Export-Csv .\notexists.csv -NoTypeInformation -Force
}
else {
"An error occurred: $_"
} continue
}
"User '$($ADUser.SamAccountName)' exists." |
Export-Csv .\notexists.csv -NoTypeInformation -Force
}
$UserList = gc C:\temp\Output_userInfo.csv #use full path instead. .\ is relative path and could cause issues if you are not careful
$outputFilePath = "D:\Input\User&Group_Output.csv"
$finalResult = foreach ($u in $UserList)
{
#CSV takes data in a table format. So best to replicate that with a PS Cusotm object that can easily be represented ina table format.
$obj = [PSCustomObject]@{
UserName = $u
Status = ""
}
try
{
$ADUser = Get-ADUser -Identity $u -ErrorAction Stop
$obj.Status = "Exists"
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
{
$obj.Status = "Does not Exist"
}
catch
{
$obj.Status = $_.Exception.Message
}
$obj
}
$finalResult | Export-Csv -Path $outputFilePath -NoTypeInformation -Force
如果您想知道我是如何知道第一次捕获中使用的错误类型的,您可以通过模拟错误来找到它[在这种情况下, get-aduser blah
会这样做,因为这样的用户不存在]。 然后你可以用select *
展开最后一条错误消息,如图所示,查看异常类型。 或者,您也可以尝试阅读文档,但我没有那种耐心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.