powershell - 在不停止程序的情况下处理 ADIdentityNotFoundException
问题描述
我必须循环输入文件中的每个对象,对每个对象执行 Get-ADUser,并且我想在不停止循环的情况下处理 ADIdentityNotFoundException 错误。有没有更好的方法可以做到这一点(例如为了简化):
Import-Csv $input | Foreach-Object {
$manager = "BLANK"
if ($user = Get-ADUser $_."samaccountname" -properties * ) {
# I don't think I need this in an IF{} since the line below won't work
# so $manager will be equal to the last value set, "BLANK", but
# this makes it easier to understand what I want to happen
$manager = $user."manager"
# I need more properties (thus -properties *) but again just an example
}
}
本质上,如果 Get-ADUser 查找成功,则设置$manager = $user."manager"
如果不成功,不要停止循环,不要复制前一个用户的值,拥有$manager = "BLANK"
(或其他)。我对 try/catch 解决方案的问题是,ADIdentityNotFoundException
除非我添加,否则不会触发 catch -ErrorAction Stop
,这将导致程序终止的不良结果。
解决方案
我不确定你的程序为什么会终止。使用下面的示例代码循环遍历数组中的所有用户。我故意在数组的第二个值(位置 [1])中输入了不正确的用户名:
$users = "username1", "username2", "username3" #username2 is purposely incorrect
foreach ($i in $users){
try{
$user = Get-ADUser -Identity $i -Properties * -ErrorAction Stop
Write-Host "Found"
}catch{
Write-Host "Not found"
}
}
我的输出是
成立
未找到
成立
推荐阅读
- sql - 在 PostgreSQL 中按月中最近的日期过滤
- java - android MediaSession setActive(false) 不起作用
- c# - 如何使用 Angular 和 C# 下载 sat 文件
- amazon-web-services - Cloudfront 从不同位置返回 403
- mybatis - 可以在Bean上写MyBatis映射注解
- python - 如何从每个递归调用中获取值并放入单个列表中?
- loops - 对于while循环条件
- api - Github API:仅搜索尚未请求/批准的更改的打开/挂起的拉取请求
- html - 除了下面的元素之外,如何允许点击影响一个元素?
- html - 从顶部开始部分标签的背景问题