我正在使用 Powershell 替换文本文件中的字符串。
为了将file.txt中的字符串1替换为字符串2,我使用
(Get-Content file.ps1) | Foreach-Object { $_ -replace 'String 1', 'String 2'} | Set-Content file.txt
即使使用 - 和 # 等替换字符,它也能很好地工作
它需要用 [ 字符替换字符串,但它不起作用。我需要将 -state [VMstate]::stopped 替换为 -state Stopped 但它不适用于
(Get-Content TEMP_config.ps1) | Foreach-Object { $_ -replace '-state [VMstate]::stopped', '-state stopped'} | Set-Content TEMP_config.ps1
如何找到[字符?
最佳答案
替换operator使用regular expressions来匹配文本。搜索文字文本的一种方法是转义搜索文本:
$search = [regex]::escape('[MyText]')
(Get-Content file.ps1) | Foreach-Object { $_ -replace $search , 'String 2'} | Set-Content file.txt
关于scripting - [ powershell 中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8731091/