A confusing PowerShell script

I recently stumbled upon a bit of code (not important where) that had a line that looked like this:

$Something.SomethingElse -Contains 'Foo'

When I saw it, I immediately thought “they’re using the -Contains operator instead of the -Like operator or the .Contains() method.” This is a common mistake, so my radar picks it up without me even thinking about it.

I was wrong, however. The $Something variable was (probably) a list, so the dot-operator got a list of SomethingElse property values from the items in the list. Then, -Contains made sense.

I don’t think I like the dot-operator being used this way in published code. I feel like it’s less clear than something more explicit like this:

($Something | Select-Object -ExpandProperty SomethingElse) -Contains 'Foo'

or even (for this specific example at least):

 [bool]($Something | Where-Object SomethingElse -eq 'Foo')

Both of these are a bit longer than the original but I think it’s a lot clearer that we’re working with a collection of objects with a SomethingElse property and that we’re actually looking for an item in the collection, rather than accidentally using the wrong operator.

There aren’t a lot of features of PowerShell that I don’t like, but this is one that I don’t tend to use.

What about you? Do you use the dot this way?

Let me know what you think in the comments.

–Mike

One Comment

  1. I use the dot operator like this a lot although I agree with you that it’s not as clear. I’m a bit curious about the the operator’s implementation and whether or not there’s any difference in performance between the dot operator and select-object.

Comments are closed.