如何忽略存储在PowerShell字符串变量中的转义序列? [英] How to ignore escape sequences stored in PowerShell string variable?
问题描述
foreach($ file in(lspath\to\files)){
$ found = $ false
$ found = Select-String -Path $ file $ id -Quiet
if($ found){
break
}
}
不幸的是,$ id变量有时像\C或\T这样,而Select-String尝试将其解释为转义序列。这些不是有效的转义序列,所以Select-String会引发错误。它们不是作为转义序列(例如,它可以是文件路径的一部分,例如C:\Test),那么如何防止PowerShell / Select-String解释它们呢?我试过在$ id附近使用括号,没有运气。
使用静态 escape()
方法,表达式引擎来解释这些字符而不是元字符:
$ id = [regex] :: escape($ id)
您也可以将命令转到一个班轮( -path
可以收集文件):
选择字符串-Path path\toto\files\ \ * -Pattern([regex] :: escape($ id))-Quiet
In my PowerShell script, I'm running Select-String over a number of files, looking for a string passed into it via a variable ($id):
foreach ($file in (ls "path\to\files")) {
$found = $false
$found = Select-String -Path $file $id -Quiet
if ($found) {
break
}
}
Unfortunately, the $id variable sometimes things like "\C" or "\T", which Select-String tries to interpret as escape sequences. These are not valid escape sequences, so Select-String throws an error. They are not intended to be escape sequences (e.g., it could be part of a file path such as "C:\Test"), so how can I prevent PowerShell/Select-String from interpreting them as such? I've tried using parentheses around $id with no luck.
Use the static escape()
method, it instructs the regular expression engine to interpret these characters literally rather than as metacharacters:
$id = [regex]::escape($id)
You can also turn the command to a one liner (-path
can take a collection of files):
Select-String -Path path\to\files\\* -Pattern ([regex]::escape($id)) -Quiet
这篇关于如何忽略存储在PowerShell字符串变量中的转义序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!