- What am I doing wrong here?
- Why do the 2 variables not equal each other?
When I run this script
$temp1 = "@{Dhcp=Disabled}"
$temp2 = Get-NetIPInterface My_Ethernet | select Dhcp
write-host ""
write-host "1" $temp1
write-host "2" $temp2
write-host ""
if ($temp2 -eq $temp1){
write-host "IP address is Static "
}
Else {
write-host "IP address is Not Static"
}
I get this result
1 @{Dhcp=Disabled}
2 @{Dhcp=Disabled}
IP address is Not Static
CodePudding user response:
With the helpful suggestion from Mathias this is now working as expected
$temp1 = "Disabled"
$temp2 = Get-NetIPInterface My_Ethernet | select Dhcp
write-host ""
write-host ""
write-host "1" $temp1
write-host "2" $temp2.dhcp
write-host ""
write-host ""
if ($temp2.dhcp -eq $temp1){
write-host "IP address is Static "
}
Else {
write-host "IP address is Not Static"
}
CodePudding user response:
Just to complement your own effective solution:
Since your intent was to compare a property's value to another value, select -ExpandProperty Dhcp
would have returned that value directly (see the docs for Select-Object
):
if ((Get-NetIPInterface My_Ethernet | select -ExpandProperty Dhcp) -eq $temp1) { # ...
However, it would be much simpler to use direct property access, using .
, the member-access operator:
if ((Get-NetIPInterface My_Ethernet).Dhcp -eq $temp1) { # ...
Note that .Dhcp
would work even if your Get-NetIPInterface
call returned multiple objects, in which case an array of values is returned, courtesy of PowerShell's member-access enumeration feature.[1]
Finally, note that Write-Host
is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it by itself; e.g. $value
, instead of Write-Host $value
(or use Write-Output $value
); see this answer.
To explicitly print only to the display but with rich formatting, use Out-Host
, given that the .ToString()
stringification that Write-Host
uses on its input is often unhelpful - see this post.
[1] Note that PowerShell's comparison operators such as -eq
exhibit filtering behavior when their LHS is an array (collection); that is, instead of returning $true
or $false
, they then return the sub-array of matching elements - see about_Comparison_Operators.