Powershell 其中对象存储在变量中时未在ScriptBlock上过滤

Powershell 其中对象存储在变量中时未在ScriptBlock上过滤,powershell,powershell-3.0,Powershell,Powershell 3.0,我想用where子句筛选文件夹中的一组文件,如下所示: $fileParams = @{ Path = C:\Files\* Include = '*.cs' Recurse = $true } Get-ChildItem @fileParams | where {$_.Name -match ` '^(?!Status|Answer|Question).*'} 这正如预期的那样有效 问题 我的问题是,我想将正则表达式存储在配置文件中,并将其传递到我的函

我想用where子句筛选文件夹中的一组文件,如下所示:

$fileParams = @{
    Path = C:\Files\*
    Include = '*.cs'
    Recurse = $true
}    
Get-ChildItem @fileParams | where {$_.Name -match `
    '^(?!Status|Answer|Question).*'}
这正如预期的那样有效

问题

我的问题是,我想将正则表达式存储在配置文件中,并将其传递到我的函数中。这意味着筛选器脚本必须以字符串开头。当我执行以下两项操作以尝试让PowerShell执行筛选脚本时,它不会进行筛选:

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
我已经将存储在变量中的内容粘贴到变量中,并按预期过滤文件

如何对这些文件进行筛选,以便将筛选器的详细信息存储在配置文件中?我必须相信我错过了一个选择。

这对我来说很有用:

$a='^(?!2008|2011|2012).*'
$a | out-file .\filter.config
$b = gc .\filter.config
Get-ChildItem @FileParams | where {$_.Name -match $b}
(我的过滤器与我硬盘上的文件不同,但模式相似)


你能详细说明一下选项1不起作用吗?

看了你的例子后,我意识到我在配置中添加了不必要的引号。我可能应该在这个问题上睡一觉,而不是发问。谢谢你的帮助。