Deep Dive on what should be a simple cmdlet
Under the Stairs has a rather deep dive into the Get-ChildItem cmdlet. You would think that a PowerShell cmdlet that is used as often as Get-ChildItem wouldn't have many secrets or gotcha's, but Thomas points out several items that are easy to forget.
I saw a good question the other day in the PowerShell.Com Learn PowerShell Forum which related to using –Include when calling Get-ChildItem (or DIR, or LS!). The OP had a bunch of files in a folder (C:\Data) and wanted to get at just the *.txt files as follows:
Get-ChildItem –Path C:\Data –Include *.Txt
But it did not work – it returned no files at all (even though there were some in the folder. The reason is clear if you read the great help text closely: the Include switch is only active if you are also using the –Recurse parameter! Another small to make is that the –include property specifies a globbed string (I.e. a file name specified with Wild cards) and not a regular expression.
The simplest way to just get the text files form a single folder would be:
Get-ChildItem –Path C:\Data\*.Txt
Another way to get just the Text files in a given folder would be to use the –Filter parameter. The –Filter parameter is sent to the provider and is used to qualify the –Path value. You can call it like:
(read more and get more sample code)