在我的 powershell 脚本中,我为运行脚本的每个元素创建一个注册表项,并且我想在注册表中存储有关每个元素的一些附加信息(如果您指定一次可选参数,则默认情况下使用这些参数) future )。
我遇到的问题是我需要执行 Test-RegistryValue (如 here --see comment),但它似乎没有达到目的(即使条目存在它也会返回 false)。 我尝试“在其之上构建”,但我唯一想到的是:
Function Test-RegistryValue($regkey, $name)
{
try
{
$exists = Get-ItemProperty $regkey $name -ErrorAction SilentlyContinue
Write-Host "Test-RegistryValue: $exists"
if (($exists -eq $null) -or ($exists.Length -eq 0))
{
return $false
}
else
{
return $true
}
}
catch
{
return $false
}
}
不幸的是,这也不能满足我的需要,因为它似乎总是从注册表项中选择一些(第一个?)值。
有人知道如何做到这一点吗? 为此编写托管代码似乎太多了...
最佳答案
就我个人而言,我不喜欢测试函数有机会吐出错误,所以这就是我要做的。此函数还兼作过滤器,您可以使用它来过滤注册表项列表,以仅保留具有特定项的项。
Function Test-RegistryValue {
param(
[Alias("PSPath")]
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[String]$Path
,
[Parameter(Position = 1, Mandatory = $true)]
[String]$Name
,
[Switch]$PassThru
)
process {
if (Test-Path $Path) {
$Key = Get-Item -LiteralPath $Path
if ($Key.GetValue($Name, $null) -ne $null) {
if ($PassThru) {
Get-ItemProperty $Path $Name
} else {
$true
}
} else {
$false
}
} else {
$false
}
}
}
关于powershell - 测试注册表值是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5648931/