使用 powershell “switch -regex -file”,如何在默认块上获取 'not matched' 字符串?
Using powershell “switch -regex -file”, how get 'not matched' string on default block?
我正在使用一个函数来解析一个 ini 文件。我正在使用 switch -regex -file
代码来获取具有不同 RegEx 表达式的匹配行。但是现在,我想捕获与任何正则表达式都不匹配的行..
此时,我可以用默认块捕获它们,但我不知道如何显示行内容,因为 $matches[1] 为空(注释行:#$line=$matches[1]
)
¿如何在默认块上获得匹配行?
注意:一个可能的解决方案是通过匹配任何行“^(.*)$”的块来更改默认块,但我很好奇它们是否是任何方法在默认块
上获取 'not matched' 个字符串
谢谢
function CheckIniFile ($filePath)
{
switch -regex -file $FilePath
{
"^\[(.+)\]$" # Section
{
$section = $matches[1]
Write-Host "Section: $section"
continue
}
default
{
# Next line causes NullArray error
$line=$matches[1]
Write-Host "No section: $line"
continue
}
}
}
使用自动变量$_
,switch
循环中的当前对象:
switch -regex -file $FilePath
{
...
default
{
Write-Host "No section: $_"
continue
}
}
我正在使用一个函数来解析一个 ini 文件。我正在使用 switch -regex -file
代码来获取具有不同 RegEx 表达式的匹配行。但是现在,我想捕获与任何正则表达式都不匹配的行..
此时,我可以用默认块捕获它们,但我不知道如何显示行内容,因为 $matches[1] 为空(注释行:#$line=$matches[1]
)
¿如何在默认块上获得匹配行?
注意:一个可能的解决方案是通过匹配任何行“^(.*)$”的块来更改默认块,但我很好奇它们是否是任何方法在默认块
上获取 'not matched' 个字符串谢谢
function CheckIniFile ($filePath) { switch -regex -file $FilePath { "^\[(.+)\]$" # Section { $section = $matches[1] Write-Host "Section: $section" continue } default { # Next line causes NullArray error $line=$matches[1] Write-Host "No section: $line" continue } } }
使用自动变量$_
,switch
循环中的当前对象:
switch -regex -file $FilePath
{
...
default
{
Write-Host "No section: $_"
continue
}
}