Fred
Fred

Reputation: 4076

Using a wildcard in a variable for Get-ChildItem filter

Below is the code

$now = [System.DateTime]::Now

$filter = $now.ToString("MM_dd_yyyy") + "_*_S1.txt"
Write-Host $filter

Get-ChildItem -filter $filter | % {Write-Host $_}# Select-Object -OutVariable $files

Write-Host $files.GetType()

I can take the output of the 'Write-Host $filter' statement and paste it into PowerShell and get the results I expect, so I know the filter is correct. Is it because I'm using a variable in the get-childitem call? How would one go about doing this.

Upvotes: 1

Views: 5561

Answers (1)

alroc
alroc

Reputation: 28154

You're misusing -OutVariable. It's expecting the name of the variable without the $. So you should be using Select-Object -OutVariable files.

But your code is very un-PowerShell-y. Using the pipeline & Select-Object is completely unnecessary here. Try this instead.

$filter = $(get-date -f "MM_dd_yyyy") + "_*_S1.txt";
$files = Get-ChildItem -filter $filter;

Upvotes: 1

Related Questions