我正在尝试从Active Directory获取用户。用户列表显示在文件users.txt中。我在进行批量查询时,我希望在保留标题(列名称)时以CSV格式导出所有详细信息。我还想处理文件errors.txt中的错误。
这是我代码中的一个片段:
$Users = Get-Content .\users.txt
try {
$Users | Get-ADUser -Properties * | select * | Export-Csv export.csv
} catch {
$_ | Out-File errors.txt -Append
}
但是我在屏幕上出现错误而不是文件。例如:
Get-ADUser : Cannot find an object with identity: 'admin' under: 'DC=test,DC=dev,DC=net'. At line:2 char:14 + $Users | Get-ADUser -Properties * | select * | Export-Csv export.csv + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (admin:ADUser) [Get-ADUser], ADIdentityNotFoundException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
我不想使用像foreach
这样的循环,因为我无法附加到CSV文件。我也失去了列名。
问题是当我为多个用户执行$Users | Get-ADUser
时如何处理文件中的错误?
答案 0 :(得分:1)
这很可能是因为没有正确设置ErrorAction。只需将-ErrorAction Stop添加到Get-ADUser命令中,看看是否可以解决问题。否则它可能无法激活您的捕获。
详细说明,您在屏幕上看到的错误很可能不是终止错误,因此它不会激活您的捕获,因此指定-ErrorAction Stop将导致非终止错误进入在文本文件中捕获并捕获错误。但是,如果您不希望管道在此期间终止,请阅读下面的编辑。
编辑,我发现当发生非终止错误时,您可能不希望管道终止。如果是这种情况,您需要改变一些事情。
#Start by clearing out errors before you execute your pipeline code. Do not put a try catch on it.
$Error.Clear()
$Users | Get-ADUser -Properties * -ErrorAction SilentlyContinue | select * | Export-Csv export.csv
$Error | Out-File C:\TEMP\errors.txt -Append
答案 1 :(得分:0)
错误为non-terminating errors,因此try..catch
无法捕获它们。 {(3}}错误从(可能)失败的命令输出到文件,并将其余部分留给管道。顺便说一下,select *
没用,所以只需删除那部分。
$Users |
Get-ADUser -Properties * 2>> 'errors.txt' |
Export-Csv 'export.csv' -NoType