简体   繁体   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\'

Any Idea how can you replace a string having : sign in it. 任何想法如何替换具有:的字符串。 I want to change the path in a config file. 我想更改配置文件中的路径。 Simple code is not working for this. 简单的代码对此不起作用。 tried following 尝试以下

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

The Replace operator takes a regular expression pattern and '\\' is has a special meaning in regex, it's the escape character. Replace运算符采用正则表达式模式,“ \\”在正则表达式中具有特殊含义,它是转义符。 You need to double each backslash, or better , use the escape method: 您需要将每个反斜杠加倍,或者最好使用转义方法:

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

Alterntively, you can use the string.replace method which takes a string and doesn't need a special care: 或者,您可以使用string.replace方法,该方法采用字符串并且不需要特别注意:

$_.Replace($oldString,$NewString)

Try this, 尝试这个,

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

You need escape the pattern to search for. 您需要转义模式以进行搜索。

This works: 这有效:

$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

The reason that your attempt wasn't working is that -replace expects it's first parameter to be a Regular Expression. 您的尝试不起作用的原因是-replace期望它的第一个参数是正则表达式。 Simply put, you needed to escape the backslashes in the directory path, which is done by adding an additional backspace ( \\\\ ). 简而言之,您需要在目录路径中转义反斜杠,这可以通过添加额外的退格键( \\\\ )来完成。 It expects the second parameter to be a string, so no changes need to be done there. 它期望第二个参数是一个字符串,因此不需要在那里进行任何更改。

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

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