scripting - [ powershell 中的字符

标签 scripting powershell

我正在使用 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/

相关文章:

python - Tensorflow GPU - 导入错误 : Could not find 'nvcuda.dll'

windows - 哪些工具和语言可用于 Windows shell 脚本?

powershell - 使用cmd中的许多参数调用Powershell脚本

bash - 如何基于某些字符串提取一行和之前的一行

azure - Powershell 和 Azure 资源资源管理器显示不同的属性集

shell - 如何从 shell 脚本运行 ant 脚本?

bash - 为什么管道使折叠函数无法保持其新定义?

powershell - 如果服务正在运行,则保存到文件;如果未保存,则保存到另一个文件

exception - Powershell导出不起作用

linux - 寻找一个 bash 脚本来在 linux 服务器上运行具有不同输入的程序