Scripting [powershell中的角色]

Scripting [powershell中的角色],scripting,powershell,Scripting,Powershell,我正在使用Powershell替换文本文件中的字符串 对于将file.txt中的字符串1替换为字符串2,我使用 它甚至可以很好地用于替换字符,如-和# 它需要用[character]替换字符串,但它不起作用。我需要替换-state[VMstate]::停止为-state stopped,但它不起作用 (Get-Content TEMP_config.ps1) | Foreach-Object { $_ -replace '-state [VMstate]::stopped', '-state s

我正在使用Powershell替换文本文件中的字符串

对于将file.txt中的字符串1替换为字符串2,我使用

它甚至可以很好地用于替换字符,如-和#

它需要用[character]替换字符串,但它不起作用。我需要替换-state[VMstate]::停止为-state stopped,但它不起作用

(Get-Content TEMP_config.ps1) | Foreach-Object { $_ -replace '-state [VMstate]::stopped', '-state stopped'} | Set-Content TEMP_config.ps1
如何找到替换用于匹配文本的[字符?

替换用于匹配文本。搜索文本的一种方法是转义搜索文本:

$search = [regex]::escape('[MyText]')
(Get-Content file.ps1) | Foreach-Object { $_ -replace $search , 'String 2'} | Set-Content file.txt

您只需退出
[

$_ -replace '-state \[VMstate]::stopped', '-state stopped'

或者使用
[Regex]::escape
如果您不确定要转义什么

您可以使用“\[”而不是“[”(前缀为反斜杠)来转义[character

@RicardoPolo,很高兴您发现这很有用。如果您不介意,请花点时间将您找到的解决问题的答案标记为已接受的答案。谢谢。
$_ -replace '-state \[VMstate]::stopped', '-state stopped'