繁体   English   中英

包括传递字符串:Powershell脚本中-Replace Variable的符号

[英]Passing string included : signs to -Replace Variable in powershell script

$FilePath = 'Z:\next\ResourcesConfiguration.config'
$oldString = 'Z:\next\Core\Resources\'
$NewString = 'G:\PublishDir\next\Core\Resources\'

任何想法如何替换具有:的字符串。 我想更改配置文件中的路径。 简单的代码对此不起作用。 尝试以下

(Get-Content $original_file) | Foreach-Object {
 $_ -replace $oldString, $NewString
 } | Set-Content $destination_file

Replace运算符采用正则表达式模式,“ \\”在正则表达式中具有特殊含义,它是转义符。 您需要将每个反斜杠加倍,或者最好使用转义方法:

$_ -replace [regex]::escape($oldString), $NewString

或者,您可以使用string.replace方法,该方法采用字符串并且不需要特别注意:

$_.Replace($oldString,$NewString)

尝试这个,

$oldString = [REGEX]::ESCAPE('Z:\next\Core\Resources\')

您需要转义模式以进行搜索。

这有效:

$Source = 'Z:\Next\ResourceConfiguration.config'
$Dest = 'G:\PublishDir\next\ResourceConfiguration.config'
$RegEx = "Z:\\next\\Core\\Resources"
$Replace = 'G:\PublishDir\next\Core\Resources'

(Get-Content $FilePath) | Foreach-Object { $_ -replace $RegEx,$Replace } | Set-Content $Dest

您的尝试不起作用的原因是-replace期望它的第一个参数是正则表达式。 简而言之,您需要在目录路径中转义反斜杠,这可以通过添加额外的退格键( \\\\ )来完成。 它期望第二个参数是一个字符串,因此不需要在那里进行任何更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM