Monday, October 10, 2011

Finding files with PowerShell without ‘and’

There is simply something intrinsically simply about using a selection statement with an “and” in it.

I constantly want to select for a file using a where clause with an '”and” – where just does not like this.  The error that I get each time I try and do this is: “Unexpected token 'and' in expression or statement.”

To get around that I started using a double pipe.

Now, I have to admit, I am not a PowerShell professional.  And many PowerShell one-liners leave me stumped when I try to read and understand what is happening.

Let me try to give you this one.

My goal – find a particular MSI file that exists in a folder.

There could be multiple MSI files, and there could be multiple files with the same name before the extension.  So I have to filter the mess.

I instinctively want to write the line this way:

$msiFile = get-childitem $exPath | where ({$_.Extension -match "msi"} and {$_.Name -match "WindowsIdentityFoundation"})

However, this gives me “unexpected token ‘and’” error all the time.  The quick solution is a double filter accomplished using a pipe and a pipe.

If I write the line this way it works:

$msiFile = get-childitem $exPath | where {$_.Extension -match "msi"} | where {$_.Name -match "WindowsIdentityFoundation"}

What is happening here? 

First is the get-childitem at the literal path $exPath.  Then that gets piped to the MSI filter selecting the extension.  Then that gets piped to the name filter selecting the correct MSI.  The end result gets returned to my variable $msiFile.

No comments: