r/PowerShell • u/jOY_HUNT • Jan 22 '26
Question anyone know whats going on with this logic?
$ping is a string that includes the text Lost = 0 among other text.
both of these return true:
if ($ping -like "*Lost = 0*")
if ($ping -notlike "*Lost = 0*")
huh?
and just to test, this returns false:
if (-not($ping -like "*Lost = 0*"))
what's going on? am i dumb?
3
Upvotes
8
u/catnip-catnap Jan 22 '26
Since it's ping result, not sure how you got it but it's probably an array of strings. Which has lines that are like your condition, and lines that aren't, so it returns true either way. Easy fix would be to do the test on the joined array.
4
u/BlackV Jan 22 '26 edited Jan 22 '26
you dont say how your running
ping, but validate your data firstwhat does
return, and what does
return, this would likely give you an answer to your question
ping.exeis NOT powershell so is not providing the same output as a powershell cmdlet would givenext, you are adding some extra unneeded handling using
invoke-expression, tryhave you looked at
test-connection? is is specifically the loss value you're looking for ?you could also look at this script
https://github.com/nerdstaunch/easy_packetloss_tracker
2
u/surfingoldelephant Jan 22 '26 edited Jun 30 '26
See
about_Comparison_Operatorscommon features.Equality/matching operators act like a filter and return all matching elements when the left-hand side (LHS) operand is a collection.
In this case,
$pingis an array of strings.-likereturns strings that match*Lost = 0*and-notlikereturns strings that don't. Non-empty strings are truthy, so are coerced to$trueby theifstatements.The operators will only directly return a boolean when the LHS operand is scalar (non-collection).
Also note that operator filtering always returns an array (
[Object[]]), even if there are no matching elements.2
u/Sure_Fold9386 Jan 22 '26
Use Test-NetConnection as opposed to ping.exe
1
u/Vern_Anderson Jan 22 '26
My opinion is that whomever wrote it was looking at the lost packets string to determine something
1
u/jsiii2010 Jan 22 '26
If this is literally the windows ping command, you can test $lastexitcode or $? intead.
-1
u/toni_z01 Jan 22 '26
quite simple - u ran the cmd utility ping which results in a outpout like this:
Pinging192.168.0.75with 32 bytes of data:Reply from 192.168.0.75: bytes=32 time<1ms TTL=128Reply from 192.168.0.75: bytes=32 time<1ms TTL=128Reply from 192.168.0.75: bytes=32 time<1ms TTL=128Reply from 192.168.0.75: bytes=32 time<1ms TTL=128Ping statistics for 192.168.0.75:Approximate round trip times in milli-seconds:Minimum = 0ms, Maximum = 0ms, Average = 0msSo for sure both statements are true - all lines of the output, which is an array of strings, are evaluated.
I think you better extract that IP and avoid invoke-expression completely:
5
u/[deleted] Jan 22 '26 edited Jan 22 '26
[removed] — view removed comment