首页 > 解决方案 > 如何将项目属性与字符串值进行比较

问题描述

我对 PowerShell 比较陌生,无法理解为什么我最初的尝试失败了。我正在尝试验证 MS Office 的位版本并对其执行操作。无论出于何种原因,在我在这里的实际问题中找到解决方案之前,字符串都没有正确比较。非常感谢帮助理解以下两个示例之间的区别。

第一次尝试:

$getMSBitVersion= Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" | Select-Object -Property Platform

if( $getMSBitVersion -eq "x64" ){
    Write-Host "true"
} else {
    Write-Host "false"
}

工作解决方案:

$getMSBitVersion= (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" -Name Platform).Platform

if( $getMSBitVersion -eq "x64" ){
    Write-Host "true"
} else {
    Write-Host "false"
}

我的假设是第一个是输出一个对象而不是字符串,因此无法进行比较。如果是这种情况,工作解决方案是唯一的方法/最好的方法吗?

标签: powershell

解决方案


Thank you Mathias and Abraham.

From what I gather, the following are confirmed methods on how to make the desired comparison.

1: This will scope into the object property of "Platform" by using dot notation and return the string value instead of the whole object.

$getMSBitVersion= (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" -Name Platform).Platform

if( $getMSBitVersion -eq "x64" ){
    Write-Host "true"
} else {
    Write-Host "false"
}

2: This will take all the properties of the Path and pass through to Select-Object. Select-Object will take and expand the "Property" object and return it as a string.

$getMSBitVersion= Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" | Select-Object -ExpandProperty Platform

if( $getMSBitVersion -eq "x64" ){
    Write-Host "true"
} else {
    Write-Host "false"
}

I was unable to get this solution to function correctly, but should, in theory, work.

3: This, in theory, should work, but the two objects are recognized differently and do not compare as intended.

$getMSBitVersion= Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" | Select-Object -Property Platform
$test= @{Platform="x64"}

if( Compare-Object $getMSBitVersion $test ){
    Write-Host "true"
} else {
    Write-Host "false"
}

推荐阅读