如何修复PowerShell中“找不到匹配参数名RegSetting”的错误
修复PowerShell注册表查询报错及逻辑问题
错误原因
- 参数不存在:
Get-ItemPropertycmdlet 没有-RegSetting这个参数,这是报错的直接原因。 - 逻辑顺序错误:你在
ForEach循环外就调用了未定义的$WUSetting变量;而且循环里只是重复输出提前定义的$RegValue,根本没遍历数组中的注册表项去执行查询。
修复后的代码
$WUSettingsArray = @( "AutoRestartDeadlinePeriodInDays", "AutoRestartNotificationSchedule", "AutoRestartRequiredNotificationDismissal", "BranchReadinessLevel", "DeferFeatureUpdates", "DeferFeatureUpdatesPeriodInDays", "DeferQualityUpdates", "DeferQualityUpdatesPeriodInDays", "DisableDualScan", "DoNotConnectToWindowsUpdateInternetLocations", "ElevateNonAdmins", "EngagedRestartDeadline", "EngagedRestartSnoozeSchedule", "EngagedRestartTransitionSchedule", "PauseFeatureUpdatesStartTime", "PauseQualityUpdatesStartTime", "ScheduleImminentRestartWarning", "ScheduleRestartWarning", "SetAutoRestartDeadline", "SetAutoRestartNotificationConfig", "SetAutoRestartNotificationDisable", "SetAutoRestartRequiredNotificationDismissal", "SetEDURestart", "SetEngagedRestartTransitionSchedule", "SetRestartWarningSchd", "WUServer", "WUStatusServer" ) $WURegKey = "HKLM:Software\Policies\Microsoft\Windows\WindowsUpdate" # 遍历数组中的每个注册表项 ForEach ($WUSetting in $WUSettingsArray) { # 尝试获取指定项的值,忽略不存在的项避免报错 $RegValue = Get-ItemPropertyValue -Path $WURegKey -Name $WUSetting -ErrorAction SilentlyContinue # 根据值是否存在输出对应信息 if ($RegValue) { Write-Output "路径: $WURegKey | 项: $WUSetting | 值: $RegValue" } else { Write-Output "路径: $WURegKey | 项: $WUSetting | 未找到该项" } }
代码说明
- 用
@()直接初始化数组,比多次+=更简洁高效。 - 使用
Get-ItemPropertyValue直接获取单个注册表项的值,比Get-ItemProperty更精准,无需处理多余属性。 - 添加
-ErrorAction SilentlyContinue忽略项不存在的报错,避免脚本中断。 - 将查询操作放到
ForEach循环内部,确保逐个处理数组中的每个注册表项。
内容的提问来源于stack exchange,提问作者GrayVi02
相关产品推荐
相关产品推荐

