如何编写PowerShell条件语句检查注册表HasLUAShield值是否存在
PowerShell脚本实现MSI右键管理员运行(含存在性检查)
核心问题解决:检查HasLUAShield值是否存在
Get-ItemPropertyValue在目标值不存在时会直接报错,无法直接用来判断存在性。可以通过两种可靠方式检测:
方式1:通过Get-ItemProperty获取属性集合后判断
先读取注册表项的所有属性,再检查HasLUAShield是否在属性列表中:
$runasKeyPath = "HKCR:\Msi.Package\shell\runas" # 读取属性,抑制不存在时的报错 $keyProps = Get-ItemProperty -Path $runasKeyPath -ErrorAction SilentlyContinue # 判断HasLUAShield是否存在 if (-not $keyProps -or $null -eq $keyProps.HasLUAShield) { # 不存在则添加,HasLUAShield是无值的字符串类型 New-ItemProperty -Path $runasKeyPath -Name "HasLUAShield" -PropertyType String -Value "" -Force | Out-Null }
方式2:用try/catch捕获Get-ItemPropertyValue的报错
利用报错逻辑判断值是否存在:
$runasKeyPath = "HKCR:\Msi.Package\shell\runas" try { # 尝试获取值,报错则进入catch Get-ItemPropertyValue -Path $runasKeyPath -Name "HasLUAShield" -ErrorAction Stop } catch { # 值不存在,执行添加操作 New-ItemProperty -Path $runasKeyPath -Name "HasLUAShield" -PropertyType String -Value "" -Force | Out-Null }
完整脚本(含所有项的存在性检查)
这个脚本会依次检查并创建所需注册表项、值,避免重复操作:
# 定义注册表路径变量,便于维护 $msiShellRoot = "HKCR:\Msi.Package\shell" $runasKey = Join-Path -Path $msiShellRoot -ChildPath "runas" $commandKey = Join-Path -Path $runasKey -ChildPath "command" $commandDefaultValue = "C:\Windows\System32\msiexec.exe /i `"%1`" %*" # 1. 检查并创建runas子项 if (-not (Test-Path -Path $runasKey)) { New-Item -Path $runasKey -Force | Out-Null Write-Host "已创建runas子项" } else { Write-Host "runas子项已存在" } # 2. 检查并添加HasLUAShield值 $keyProps = Get-ItemProperty -Path $runasKey -ErrorAction SilentlyContinue if (-not $keyProps -or $null -eq $keyProps.HasLUAShield) { New-ItemProperty -Path $runasKey -Name "HasLUAShield" -PropertyType String -Value "" -Force | Out-Null Write-Host "已添加HasLUAShield值" } else { Write-Host "HasLUAShield值已存在" } # 3. 检查并创建command子项及默认值 if (-not (Test-Path -Path $commandKey)) { New-Item -Path $commandKey -Force | Out-Null New-ItemProperty -Path $commandKey -Name "(Default)" -PropertyType ExpandString -Value $commandDefaultValue -Force | Out-Null Write-Host "已创建command子项并设置默认值" } else { # 检查现有默认值是否正确,不正确则更新 $currentValue = Get-ItemPropertyValue -Path $commandKey -Name "(Default)" -ErrorAction SilentlyContinue if ($currentValue -ne $commandDefaultValue) { Set-ItemProperty -Path $commandKey -Name "(Default)" -Value $commandDefaultValue -Force | Out-Null Write-Host "已更新command子项的默认值" } else { Write-Host "command子项的默认值已正确存在" } }
关键说明
HasLUAShield是一个无值的字符串类型注册表项,所以设置-PropertyType String -Value ""即可显示UAC盾牌图标- 使用
Out-Null抑制命令的冗余输出,让脚本运行更简洁 - command子项的默认值需用
(Default)作为名称,类型设为ExpandString确保"%1"能正确解析为选中的MSI文件路径
内容的提问来源于stack exchange,提问作者Christopher Cass
相关产品推荐
相关产品推荐

