PowerShell脚本优化:AD不存在设备时保留输出行并标记错误
解决AD计算机查询行不匹配问题的脚本
修改后的脚本可实现无论设备是否存在于AD中,都会输出对应行,不存在时会明确标记错误状态:
cls Get-Content -Path "$home\Desktop\computers.txt" | ForEach-Object { $computerName = $_ # 跳过文件中的空行 if ([string]::IsNullOrWhiteSpace($computerName)) { return } try { # 通过-ErrorAction Stop将非终止错误转为终止错误,让try/catch可以捕获 $adComputer = Get-ADComputer $computerName -Properties Name, CanonicalName, Enabled, IPv4Address, OperatingSystem, OperatingSystemVersion, LastLogonTimeStamp, Description -ErrorAction Stop # 查询成功时构造输出对象 [PSCustomObject]@{ Name = $adComputer.Name CanonicalName = $adComputer.CanonicalName Enabled = $adComputer.Enabled IPv4Address = $adComputer.IPv4Address OperatingSystem = $adComputer.OperatingSystem OperatingSystemVersion= $adComputer.OperatingSystemVersion LastLogonTime = if ($adComputer.LastLogonTimeStamp) { [DateTime]::FromFileTime($adComputer.LastLogonTimeStamp).ToString('dd-MM-yyyy_hh:mm:ss') } else { "无登录记录" } Description = $adComputer.Description Status = "正常" } } catch { # 查询失败时构造带错误标记的对象 [PSCustomObject]@{ Name = $computerName CanonicalName = $null Enabled = $null IPv4Address = $null OperatingSystem = $null OperatingSystemVersion= $null LastLogonTime = $null Description = $null Status = "AD中不存在或查询错误: $($_.Exception.Message)" } } } | Out-GridView
核心修改点说明:
- 强制捕获错误:给
Get-ADComputer添加-ErrorAction Stop参数,将原本的非终止错误转为终止错误,让try/catch可以捕获设备不存在的情况。 - 统一输出结构:无论查询成功或失败,都输出结构完全一致的自定义对象,保证输出行数与输入的
computers.txt完全匹配。 - 错误状态标记:新增
Status字段,明确区分正常设备与异常设备,失败时会显示具体错误信息。 - 空值兼容处理:对
LastLogonTimeStamp做非空判断,避免空值转换时报错,空值时显示"无登录记录"。 - 空行过滤:跳过文件中的空行,避免无效查询。
如果需要导出为CSV文件,只需将Out-GridView替换为:
Export-Csv -Path "$home\Desktop\ADComputerReport.csv" -NoTypeInformation -Encoding UTF8
内容的提问来源于stack exchange,提问作者Sabitech
相关产品推荐
相关产品推荐

