PowerShell脚本第二个elseif分支单次运行不执行问题求助
问题根因
- 异常设备遍历逻辑存在变量覆盖缺陷:两个ForEach循环遍历异常设备列表时,每次循环都会直接覆盖
$test、$testTwo变量,循环结束后两个变量仅保留最后一个被遍历的异常设备的标识信息,其余设备的标识全部丢失。 - 驱动匹配逻辑存在顺序依赖:第一次运行脚本时,
$test存储的设备匹配到对应驱动完成安装后,设备异常状态消除,第二次运行脚本时Get-WmiObject返回的异常设备列表已更新,$test才会存储剩余异常设备的信息,因此需要运行两次才能完成全部驱动安装。 - 可选优化点:
Get-WmiObject已在PowerShell中被弃用,同等功能可替换为Get-CimInstance,执行效率和兼容性更好。
修正后脚本
修正逻辑为提前收集所有异常设备的全部标识信息,单次遍历驱动文件即可完成全部匹配安装:
# 收集所有状态异常的即插即用设备 $problemDevices = Get-CimInstance Win32_PnPEntity | Where-Object { $_.ConfigManagerErrorCode -ne 0 } # 提取所有异常设备的HardwareId、CompatibleID(过滤空值) $allHardwareIds = $problemDevices.HardwareId | Where-Object { $_ } | ForEach-Object { $_[0] } $allCompatibleIds = $problemDevices.CompatibleID | Where-Object { $_ } | ForEach-Object { $_[0] } # 读取驱动文件夹下所有inf文件 $folderWithDrivers = "C:\Users\Tech\Desktop\Drivers" $driverInfList = Get-ChildItem -Path $folderWithDrivers -Include *.inf -Recurse # 遍历所有驱动文件匹配安装 foreach ($inf in $driverInfList) { $infContent = Get-Content -Path $inf.FullName -Raw $isHardwareMatch = $allHardwareIds | Where-Object { $infContent.Contains($_) } $isCompatibleMatch = $allCompatibleIds | Where-Object { $infContent.Contains($_) } if ($isHardwareMatch -or $isCompatibleMatch) { pnputil /add-driver $inf.FullName /install Write-Host "驱动安装成功:$($inf.Name)" } else { Write-Host "未匹配到对应设备:$($inf.Name)" } }
内容的提问来源于stack exchange,提问作者Costa
相关产品推荐
相关产品推荐

