powershell - Powershell 脚本检查用户是否存在于 Active Directory 中并导出到 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 *
并查看异常类型。或者,您也可以尝试阅读文档,但我没有那种耐心。
推荐阅读
- angular - 当从同一级别访问 Angular 中的应用程序时,服务中的数据不可用
- java - 如何为 webSite.getSources().size() 修复此 NullPointerException;
- java - 可视化一般依赖关系
- reactjs - 我无法从 App 组件中的 Redux 商店中获取价值
- google-analytics - 如何查看/跟踪在我的 google 分析帐户上显示 +3 页面的用户?
- mongodb - Mongodb / mongoose聚合 - 计算嵌套文档中字段的字符串出现次数它返回具有相同名称的_id - 计数是正确的
- python - 使用 pairwise_distances_chunked 计算最近邻搜索
- r - 基于模式 R 从一个向量中创建多个向量
- javascript - 使用已保存变量的 javascript 插值
- python - 在 pygame 中发出运行函数