powershell - XML文件中的条件替换

标签 powershell powershell-2.0 powershell-3.0

我正在使用PowerShell递归替换XML文件中的文本。该脚本可以很好地替换。但是,XML文件还具有不应替换的文件路径。这是当前正在使用的脚本

if ( $content -match ' web site | web-site ' ) {
    $content -replace ' web site ',' New Site ' -replace ' web-site ',' New Site ' |
        Out-File $file.FullName -Encoding utf8

例如,如果XML文件具有

<title>web site</title>
<subtitle>web-site</subtitle>
<path>c:/web site/website.xml</path>

预期的输出应如下所示。文件路径中的匹配文本应被忽略。如果字符串在/web site//web-site.xml之间,如何添加条件以忽略字符串?

<title>New Site</title>
<subtitle>New Site</subtitle>
<path>c:/web site/website.xml</path>

最佳答案

这是快速修复,但是请注意是一个更强大的解决方案,它将使用PowerShell的XML解析功能:请参阅Ansgar Wiecher's helpful answer:

注意:
-此答案假定目标字符串与XML文档的语法元素(例如元素名称和属性名称(碰巧适用于所讨论的特定字符串))不冲突,这说明了为什么使用真正的XML解析器是更好的选择。

$content = @'
<doc>
<title>web site</title>
<subtitle>web-site</subtitle>
<path>c:/web site/website.xml</path>
</doc>
'@

$modifiedContent = $content -replace '(^|[^/])web[ -]site([^/]|$)', '$1New Site$2'
# Replace 'web site' and 'web-site' if not preceded or followed by a '/'.
# Note: `web[ -]site` is the equivalent of `web site|web-site`

if ($modifiedContent -cne $content) { # If contents have changed, save.
  Out-File -InputObject $modifiedContent $file.FullName -Encoding utf8
}

关于powershell - XML文件中的条件替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38534986/

相关文章:

powershell - 带括号的环境变量导致 “unexpected token”错误

powershell - 在 Powershell 中创建文件夹和文件

powershell - 脚本中的参数问题

使用 CloudDrive Azure 示例时出现 Powershell 错误

powershell - 从Powershell POST时如何解析 “Content”输出?

powershell - 如何使用Powershell扩展文件内容

powershell - 将文件读入行分隔数组

powershell - 查找角色位置并更新文件名

Powershell - 添加广告组成员对象类 :contact to a distribution group error Cannont find[.。]

powershell - PSSessionStateBroken 在计划任务中带有 start-job -credential