创建用于检查注册表值的 If 语句

问题描述 投票:0回答:2

我正在编写一个脚本来编辑注册表值,以允许右键单击 msi 文件以管理员身份运行。这涉及在以下位置添加一个子项:

HKCR:\msi.package\shell

得到

HKCR:\msi.package\shell\runas

然后给runas called添加一个值

HasLUAShield

还有另一个 runas 的子项:

HKCR:\Msi.Package\shell\runas\command

价值

C:\Windows\System32\msiexec.exe /i \"%1\" %*

我已经能够成功创建它们,但我希望在添加它们之前首先检查它们是否存在。我知道我可以检查两者:

Test-Path -Path HKCR:\Msi.Package\shell\runas

Test-Path -Path HKCR:\Msi.Package\shell\runas\command

但是检查 HasLUAShield 的值变得有点困难。我发现我可以通过以下方式在值列表中获取它:

Get-ItemProperty -Path 'HKCR:\msi.package\shell\runas'

但我不知道如何只检查 HasLUAShield 并找出一种方法将其添加到 if 语句以确定我是否需要添加该值。有人有建议吗?我也试过:

Get-ItemPropertyValue -Path 'HKCR:\msi.package\shell\runas' -Name HasLUAShield

但这什么也没有返回。

powershell registry
2个回答
0
投票

在 PowerShell 中,您可以使用 Get-ItemProperty cmdlet 检索注册表值,然后使用 if 语句检查该值是否与预期值匹配。这是一个例子:

$value = Get-ItemProperty -Path "HKCU:\Software\MyApp" -Name "MyValue"

if ($value -eq "expected_value") {
    # Do something if the registry value matches the expected value
} else {
    # Do something else if the registry value doesn't match the expected value
}

在此示例中,我们使用 Get-ItemProperty cmdlet 检索 HKCU:\Software\MyApp 注册表路径中注册表项 MyValue 的值。我们将值存储在变量 $value 中。

然后我们使用 if 语句来检查 $value 的值是否与预期值匹配。如果值匹配,我们将执行 if 语句的第一个块中的代码。如果值不匹配,我们将执行 else 块中的代码。

您可以将“HKCU:\Software\MyApp”和“MyValue”替换为您要检查的实际注册表路径和值名称。您还可以将“expected_value”替换为您希望在注册表中找到的实际值。请注意,如果注册表中不存在键或值,Get-ItemProperty 将返回 null,因此如果需要,您可能需要单独处理这种情况。


0
投票

你真的不需要

Get-ItemPRoperty
Get-ItemPropertyValue
因为这个值没有数据——它只是存在作为一个标志。 Get-Item <KeyPath> 返回的
RegistryKey
对象有一个名为“Property”的 NotePropety,它是键下值的
String[]

PS C:\> (Get-Item HKCR:\batfile\Shell\runas).Property
HasLUAShield

诸如此类:

$keyPath = HKCR:\Msi.Package\Shell\runas
$keyValue = 'HasLUAShield'
$command = '\System32\msiexec.exe /i "%1" %*'

If ( ! (Test-Path $keyPath))
{
    # runas key doesn't exist -> create it.
}
$key = Get-Item $keyPath
If ($keyValue -notIn $key.Property )
{
    New-ItemProperty -Path $keyPath -Name $keyValue
}
If ( ! (Test-Path "$keyPath\Command"))
{
    # "Command" subkey doesn't exist -- create it
}
$splat = @{
    'Path'  = "$keyPath\Command"
    'Name'  = '(Default)'
}
If ((Get-ItemPropertyValue $splat) -notMatch [Regex]::Escape("$env:SystemRoot$command"))
{
    Set-ItemProperty $splat -Value "%SystemRoot%$Command" -Type ExpandString
}
© www.soinside.com 2019 - 2024. All rights reserved.