Confused About String Comparisons in PowerShell
Asked by
free-body-diagram
I'm having some issues with string comparisons in PowerShell. I have a variable, `$ping`, which includes the text `Lost = 0` along with other data. Here's the strange part: both of these conditions seem to return true:
`if ($ping -like "*Lost = 0*")`
`if ($ping -notlike "*Lost = 0*")`
However, when I run this condition, it returns false:
`if (-not($ping -like "*Lost = 0*"))`
I'm really confused! Can anyone help clarify what's happening here? Am I missing something obvious?
Answers
Seems like you're not validating your data correctly! Run the conditions step by step and see what `$ping -like "*Lost = 0*"` and `$ping -notlike "*Lost = 0*"` are actually returning. Since `ping.exe` isn't a PowerShell cmdlet, it might not be returning data in the expected format. To solve this, try using `Test-Connection` instead.
Reply to this answer
It sounds like the way you're getting your `$ping` result might be affecting the comparison. The `ping` result could be an array of strings, where some lines include `Lost = 0` and others don't. This can lead to some confusing results! A straightforward fix would be to test against a joined array instead, like `-join` to combine them. It makes sure you're checking the content correctly. Let me know if you want more details on that!
Reply to this answer
Hey! First off, donโt be too hard on yourself! Make sure you check how youโre running the `ping` command. You can run `ping` without `Invoke-Expression` to get cleaner output. Try using: `$ping = & ping 192.168.1.100`. This approach might give you cleaner data. Also, have you checked out the `Test-Connection` cmdlet? It's specifically designed for testing network connectivity and might give you the loss value you need.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions