如何使用包含 $value 的模式 Select-String

How to Select-String with pattern that contains $value

如何在txt文件中搜索以$开头的字符串?

例如:

Get-Content $file | Select-String -pattern 'VALUE="$USERPROFILE"'

谢谢

如果您只想查找以“$”开头的字符串,您可以使用类似于下面的方法。

param(
    [string] $file = "$PSScriptRoot\test.txt",
    [string] $pattern = "$*"
)

$stringsBeginningWithPattern = (Get-Content $file).Split() | Where-Object {
    $_ -like $pattern
}

$stringsBeginningWithPattern


使用 [regex]::Escape() 方法正确转义用于正则表达式模式的逐字字符串:

$pattern = 'VALUE="{0}"' -f [regex]::Escape('$USERPROFILE')
Get-Content $file | Select-String -Pattern $pattern

或使用 -SimpleMatch 开关表示您根本不想使用正则表达式:

Get-Content $file | Select-String -pattern 'VALUE="$USERPROFILE"' -SimpleMatch