我编写了以下命令管道:
get-process | where {$_.Path -notmatch ${env:SystemRoot} -and $_.Path -notmatch ${env:ProgramFiles} -and $_.Path -notmatch ${env:ProgramFiles(x86)} | select path, name我收到错误:
parsing "C:\Program Files" - Malformed \p{X} character escape.
At line:1 char:22
+ get-process | where {$_.Path -notmatch $env:SystemRoot -and $_.Path -notmatch $e ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException我知道发生了什么,我做了几个测试。我使用带转义字符和不带转义字符的路径调用了Get-ChildItem cmdlet。一切工作正常。我放入了Where-Object FilterScript参数脚本块,其中包含带和不带"\“转义字符的路径。带有转义字符的路径的Where-Object运行正常,但是当我在Where-Object中放置没有转义字符的路径时,我总是得到错误。
这不是系统环境变量的问题。我用"C:\Program Files“定义了变量ProgramFilesA,用"C:\Program Files”定义了变量ProgramFilesB。当我在Where-Object中使用$env:ProgramFilesA时,我得到了错误,当我使用$env:ProgramFilesB时,一切正常。
如何在Where-Object cmdlet中调用包含路径的标准$env:变量才能无错误地运行它?
发布于 2016-02-23 18:11:05
您可以使用正则表达式进行转义。
下面的代码应该可以工作:
get-process | where {$_.Path -notmatch [Regex]::escape($env:SystemRoot) -and $_.Path -notmatch [Regex]::escape(${env:ProgramFiles(x86)}) -and $_.Path -notmatch [Regex]::escape(${env:ProgramFiles(x86)}) } | select path, name如果您试图运行不在程序文件和系统根目录的子文件夹中的进程,则可能需要修改通配符(任何以开头的路径)的匹配表达式。
发布于 2016-02-23 19:47:59
这个问题是因为您正在使用-match,这是一个使用正则表达式的运算符,并且您没有正确地转义正则表达式元字符。这就是该错误试图告诉您的:
Malformed \p{X} character escape
\p是“程序文件”中的P。正则表达式中的\p是used for matching code points。
您可以直接使用-like。我们在这里使用双引号来允许变量扩展。
get-process | where {$_.Path -notlike "$($env:SystemRoot)*" -and $_.Path -notlike "$($env:ProgramFiles)*" -and $_.Path -notlike "(${env:ProgramFiles(x86)})*"}如果您确实想使用正则表达式,那么也可以收集这些环境变量并使用它们生成一个适当的正则表达式字符串。
$regex = "^(" + (($env:SystemRoot, $env:ProgramFiles, ${env:ProgramFiles(x86)} | ForEach-Object{[regex]::Escape($_)}) -join "|") + ")"
Get-Process | Where-Object {$_.Path -notmatch $regex}所以现在匹配的正则表达式字符串是"^(C:\Windows|C:\Program\ Files|C:\Program\ Files\ (x86))“
https://stackoverflow.com/questions/35574267
复制相似问题