Scripting. Powershell, VMware, Windows, Active Directory & Exchange. All that kind of stuff…..
RSS icon Email icon Home icon
  • PowerShell v3 – New -in Operator

    Posted on October 12th, 2012 Jonathan Medd 2 comments

    Hidden away amongst some of the new language features in PowerShell v3 are two new operators: -in and -notin. Previously you could use -contains, say in an example like the following: does the variable $fruits contain the string ‘Apple’?

    
    $fruits = 'Apple','Orange','Pear'
    $fruits -contains 'Apple'
    $fruits -contains 'Banana'
    
    

     

    There’s nothing wrong with this approach, but in many examples for me it seemed to be the wrong way around from that I was naturally thinking: is the string ‘Apple’ in the variable $fruits?

    With the addition of the -in operator it’s now possible to write it this way:

    
    $fruits = 'Apple','Orange','Pear'
    'Apple' -in $fruits
    'Banana' -in $fruits
    
    

     

     

     

     

    2 responses to “PowerShell v3 – New -in Operator” RSS icon

    • They did this so you could have -contains functionality when using the shortened where-object syntax. Although I agree that -in makes more sense to me.

      In V2 you would do this:
      dir | Where { ‘.ps1′, ‘.cmd’ -contains $_.Extension }

      In V3 you can do this:
      dir | Where Extension -in ‘.ps1′, ‘.cmd’

      because the first parameter has to be the property you are checking, -contains wouldn’t work.

    • Absolutely. I prefer not to speak of this simplified syntax though ;-)


    Leave a reply