How to ignore escape sequences stored in PowerShell string variable?

后端 未结 3 1298
花落未央
花落未央 2021-01-01 12:32

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 \         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 12:48

    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
    

提交回复
热议问题