1

I'm building a powershell script to only grab files with a certain date in the string (yesterday's date) and display their names. But it doesn't seem to be going well. I've tried Googling but haven't found specifically help on what I'm trying to do:

$a = (Get-Date).AddDays(-1).ToString('yyyyMMdd')

$b = Get-ChildItem "E:\Export" -Filter {$_.Name -like '*'+$a.ToString()}

Get-ChildItem "E:\Export" -Filter *.txt |

Foreach-Object {

    If ($b -like $a)
    {
    Write-Host $b
    }

}

Any help would be appreciated.

Him_Jalpert
  • 2,476
  • 9
  • 31
  • 55

2 Answers2

4

$a IS already a string. You can't simply put a script block as a filter.

$a = (Get-Date).AddDays(-1).ToString('yyyyMMdd')
$b = Get-ChildItem "E:\Export" | Where-Object BaseName -like "*$a*"
$b

or

$b = Get-ChildItem "E:\Export\*$a*"
3

td;dr

$b = Get-ChildItem "E:\Export" -Filter ('*' + $a)

Or, using PowerShell's string expansion (interpolation):

$b = Get-ChildItem "E:\Export" -Filter "*$a"

-Filter parameter values:

  • are always [string]-typed

  • their specific syntax is provider-dependent

Since you're dealing with files, it is the FileSystem PS provider that interprets -Filter, and it expects a wildcard expression as an argument, as accepted by the underlying Windows API; the wildcard expression is implicitly matched against the file name.

Note:

  • Typically - such as in this case - such wildcard expressions work the same as PowerShell's own wildcard expressions, but the former have quirks in order to support legacy applications, while the latter offer additional features.

  • No standard provider accepts script blocks with arbitrary PowerShell code as a -Filter arguments, despite their widespread - but misguided - use with the Active Directory provider - see this answer.

To perform arbitrary filtering of output objects via script blocks in PowerShell code, pipe to the Where-Object cmdlet, as shown in LotPings' answer.

However, if feasible, use of -Filter should always be the first choice, because it filters at the source, meaning that the provider returns the already-filtered results to PowerShell (as opposed to having to filter the results after the fact, in PowerShell code), which can greatly speed up operations.

mklement0
  • 382,024
  • 64
  • 607
  • 775