我有一个变量列表:
$desa = "filtering regex for desa"
$cdo = "different regex for cdo"
等
现在,我有一个循环:
Foreach ($profilename in ("desa", "cdo")) {
# filter out data from $profilename file where regex is contained in
# variable named after the content of $profilename
}
因此,换句话说,我需要使用顶部变量之一中包含的字符串,该变量的名称是$profilename
变量的确切内容。
PowerShell可以这样做吗?
答案 0 :(得分:2)
对于我们来说,正则表达式的哈希表可能比每个单独的变量更容易:
$filters = @{
desa = "filtering regex for desa"
cdo = "different regex for cdo"
}
Foreach ($profilename in
( "desa", "cdo")
)
{
(Get-content <profilename file>) -match $filters[$profilename]
}
只需在个人资料名称后面指定密钥即可。
答案 1 :(得分:0)
正如@mjolinor所说:哈希表是一种更好的方法。但是,如果由于某种原因您必须展开“构造”变量,则可以使用$ExecutionContext
automatic variable来完成:
PS C:\> $a = 'foo'
PS C:\> $b = 'a'
PS C:\> $c = "`$$b"
PS C:\> $c
$a
PS C:\> $ExecutionContext.InvokeCommand.ExpandString($c)
foo
应用于您的代码,可能如下所示:
$desa = "filtering regex for desa"
$cdo = "different regex for cdo"
foreach ($profilename in 'desa','cdo') {
$pattern = $ExecutionContext.InvokeCommand.ExpandString("`$$profilename")
$something | ? { $_ -match $pattern } | ...
}