在cmd.exe中执行PowerShell CSV过滤命令报错,如何正确运行?
解决cmd中执行PowerShell命令的引号解析错误
你遇到的错误是因为cmd会优先解析命令中的双引号,导致PowerShell实际接收到的命令丢失了引号,引发语法错误。而在PowerShell提示符中直接执行时,PowerShell自己处理引号解析,所以没有问题。
方案1:按照cmd规则转义双引号
在cmd环境中,双引号需要用""来转义,确保PowerShell能正确识别命令中的引号:
C:\temp>powershell.exe -ExecutionPolicy Bypass -NoLogo -NoProfile -Command "(Get-Content .\FilteredANReport_5.csv | Where { $_ -notmatch "^""",""" } )"
方案2:用单引号包裹整个PowerShell命令
cmd不会解析单引号,因此可以把整个PowerShell命令用单引号包裹,同时将命令内的引号替换为单引号(PowerShell支持单引号字符串):
C:\temp>powershell.exe -ExecutionPolicy Bypass -NoLogo -NoProfile -Command '(Get-Content .\FilteredANReport_5.csv | Where { $_ -notmatch "^," } )'
优化命令(可选)
如果你的需求是过滤掉以逗号开头的行,正则表达式^,即可满足需求,无需额外引号,命令更简洁:
- PowerShell直接执行版本:
Get-Content .\FilteredANReport_5.csv | Where { $_ -notmatch '^,' } - cmd中执行版本:
powershell.exe -ExecutionPolicy Bypass -NoLogo -NoProfile -Command '(Get-Content .\FilteredANReport_5.csv | Where { $_ -notmatch ''^,'' } )'
内容的提问来源于stack exchange,提问作者Y.K.
相关产品推荐
相关产品推荐

