Home > Back-end >  Comparing Variables within Powershell
Comparing Variables within Powershell

Time:06-30

Ok. So I thought this would have been easy, but I am hitting a snag.

$var = (Get-ItemProperty "HKCU:\SOFTWARE\SAP\General" -Name "BrowserControl")."BrowserControl"
$var2 = "HKCU:\SOFTWARE\SAP\General"
$var3 =  @('1','0')
#if (($var -eq ($var3 -join'')))
#if (Compare-Object -IncludeEqual $var $var3 -SyncWindow 0)
if ($var -eq $var3)
{
    Write-Output "Registry hive exists"
    exit 1
}   
else 
{
    Write-Output "Registry hive doesn't exists"
    #New-ItemProperty -Path $var2 -name "BrowserControl" -Value "1" -PropertyType "DWORD" -Force | Out-Null
    
} 

If 1 or 0 is returned from BrowserControl, I want it to be a match. If anything else is returned, no match. If BrowserControl is set to 1, it works. If it is set to 0 or any number other than 1 it doesn't match. I know I can use else-if and add a couple more lines of code, but I was really wanting to get this to work. As you can see, I have tried different comparison methods. I also tried (0,1), ('0','1'), 0,1 for var3. None of those worked either. So... what am I missing?

CodePudding user response:

You cannot meaningfully use an array as the RHS of the -eq operator.[1]

However, PowerShell has dedicated operators for testing whether a given single value is contained in a collection (more accurately: equal to one of the elements of a collection), namely -in and its operands-reversed counterpart, -contains.

In this case, -in makes for more readable code:

if ($var -in $var3) # ...

[1] PowerShell quietly accepts an array (collection) as the RHS, but - uselessly - stringifies it, by concatenating the elements with a single space by default. E.g., '1 2' -eq 1, 2 yields $true.
By contrast, using an array as the LHS of -eq is meaningfully supported: the RHS scalar then acts as a filter, returning the sub-array of equal LHS elements; e.g. 1, 2, 3, 2 -eq 2 returns 2, 2

  • Related