为什么Where-Object -Match不接受args [1]作为PowerShell中的正则表达式?

问题描述

我创建了PoweShell脚本来更新Visual Studio项目文件中的<TreatWarningAsError>值。

<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|Win32'">
    <ClCompile>
        ...
      <TreatWarningAsError>true</TreatWarningAsError>
    </ClCompile>
    ...
</ItemDefinitionGroup>

它的第一个参数是项目文件,第二个参数是$(Configuration)|$(Platform)字符串,它允许用户选择每次更新的$(Configuration)|$(Platform)种情况。

# usage
# update_vcxproj_turn_off_treat_warnings_as_errors.ps1 notepadPlus.vcxproj "Release\|Win32"

$arg1 = $args[1]
$file = Get-Item $args[0]
$xml = [xml](Get-Content $file)
# $idg = $xml.Project.ItemDefinitionGroup | Where-Object {$_.Condition -Match $args[1]}
$idg = $xml.Project.ItemDefinitionGroup | Where-Object {$_.Condition -Match $arg1}
$idg
$idg.ClCompile.TreatWarningAsError = "false"
$xml.Save($file.Fullname)

$args[1]传递到自定义变量$arg1,然后在$arg1之后使用-Match时,脚本将提供正确的输出。

REM Command run in regular CMD
> PowerShell R:\update_vcxproj_turn_off_treat_warnings_as_errors.ps1 R:\npp_2020-08-11\notepadPlus.vcxproj "Release\`|Win32"

Condition      : '$(Configuration)|$(Platform)'=='Unicode Release|Win32'
ClCompile      : ClCompile
Link           : Link
Manifest       : Manifest
PostBuildEvent : PostBuildEvent

但是,当直接使用$args[1](运行注释行)时,不会期望脚本输出。

Condition      : '$(Configuration)|$(Platform)'=='Unicode Debug|Win32'
ClCompile      : ClCompile
Link           : Link
Manifest       : Manifest
PostBuildEvent : PostBuildEvent

Condition      : '$(Configuration)|$(Platform)'=='Unicode Debug|x64'
ClCompile      : ClCompile
Link           : Link
Manifest       : Manifest
PostBuildEvent : PostBuildEvent

Condition      : '$(Configuration)|$(Platform)'=='Unicode Release|Win32'
ClCompile      : ClCompile
Link           : Link
Manifest       : Manifest
PostBuildEvent : PostBuildEvent

Condition      : '$(Configuration)|$(Platform)'=='Unicode Release|x64'
ClCompile      : ClCompile
Link           : Link
Manifest       : Manifest
PostBuildEvent : PostBuildEvent

它与字符串插值无关,因为使用-Match "$($args[1])"与使用-Match $args[1]可获得相同的输出。

在Windows 10 64位版本的PowerShell 5.1和PowerShell 7.0上进行了测试。

那是怎么发生的?任何线索都值得赞赏。

解决方法

我认为Match将括号解释为通配符。

https://www.educba.com/powershell-wildcards/

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...