Question

I want to filter a set of files in a folder with a where clause like so:

$fileParams = @{
    Path = C:\Files\*
    Include = '*.cs'
    Recurse = $true
}    
Get-ChildItem @fileParams | where {$_.Name -match `
    '^(?!Status|Answer|Question).*'}

This works as expected.

Problem

My problem is that I want to store the regular expression in a config file and have it passed into my function. This means the filter script has to start as a string. When I do both of the following to try to get PowerShell to execute the filter script, it doesn't filter:

Option 1:
[String]$Filter = '^(?!Status|Answer|Question).*'
Get-ChildItem @fileParams | where {$_.Name -match $Filter}

Option 2:
$filterText = '{$_.Name -match "^(?!Status|Answer|Question).*"}'
[ScriptBlock]$filter = [ScriptBlock]::Create($filterText)
Get-ChildItem @fileParams | where -FilterScript $filter

I have taken what is stored in the variable and pasted it in for the variable and the files are filtered down as expected.

How can I go about filtering these files down so that the details of the filter are stored in a config file? I've got to believe there is an option I'm missing.

Était-ce utile?

La solution

This works for me:

$a='^(?!2008|2011|2012).*'
$a | out-file .\filter.config
$b = gc .\filter.config
Get-ChildItem @FileParams | where {$_.Name -match $b}

(My filter is different to match the files I have on my HD, but pattern is similar).

Can you elaborate on Option 1 not working ?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top