This is a quick tip for people that would like to search for multiple file types in Windows using PowerShell.
To begin, let’s look at what you would need to do using the Windows Command Shell. If you wanted to see all the files in a directory that are of type
.json. You could do something like this:
> dir *.json
But instead, what if you wanted to look for all
.json files AND
.yml at the same time? Back to the shell, you could type this:
> dir *.json *.yml
That works but the Command Shell isn’t the easiest to work with if you then wanted to process those files in other ways, programmatically. Let’s jump to PowerShell which is significantly better in that regard. Starting with the first example, we could use
> Get-ChildItem -Path .\*.json
Here, we’re asking PowerShell to show us all files in the current directory (
.\) which have the extension
.json. That’s fine, but not a huge improvement on the Command Shell. OK - what if we are interested in two types of file extension? Using the same technique as in the Command Shell, just won’t work.
> Get-ChildItem -Path .\*.json *.yml
The trick here is to refer to the documentation. Here’s the docs for the command I mean.
The bits we need to focus on are lines 2 and 4: -Path and -Include.
The -Path is used to specify the location and set of ALL files which could be used in the listing of files. So, we could for instance ask for all files in the current directory like this:
-Path .\*. What about the -Include parameter, then?
That’s used to tell PowerShell which files, from all of the files, we would like to include. So in this case, we’re after the .json and .yml files. Before I do that though, let’s take a closer look at line 4 and the syntax used in the MS help page.
The outer square brackets tell us that this command line parameter is optional, but look closer, and you can see that there are two more square brackets attached to the string segment. In this case, it’s telling us that the parameter can accept an array of strings. Here’s our final example demonstrating that using the same files as before.
> Get-ChildItem -Path .\* -Include "*.json","*.yml"
As you can see, to specify the array of strings, all we have to do is separate them with a comma and now that we are using PowerShell, we can pipe that output to another command or store the set of files as objects in a variable with something like this:
> $results = Get-ChildItem -Path .\* -Include "*.json","*.yml"
Do take a look at the manual page for
Get-ChildItem as there’s lots more you can do with this command.
Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com