繁体   English   中英

Powershell Set-Content如何替换多行

[英]Powershell Set-Content How to replace multiple lines

我有以下PowerShell脚本(我正在使用Powershell v5.1),该脚本是我从以前的文章中摘录并改编的: 使用Powershell替换文件中的多行文本,而不使用Regex

$oldCode =  @"
        <httpProtocol>
            <customHeaders>
                <clear />
            </customHeaders>
            <redirectHeaders>
                <clear />
            </redirectHeaders>
        </httpProtocol>
"@

$newCode = @"
        <httpProtocol>
            <customHeaders>
                <add name="X-Frame-Options" VALUE="SAMEORIGIN"></add>
            </customHeaders>
            <redirectHeaders>
                <clear />
            </redirectHeaders>
        </httpProtocol>
"@

$Path = "c:\Windows\System32\inetsrv\config\applicationHost.config"
$Content = (Get-Content $Path -Raw).replace($oldCode,$newCode)

Set-Content -Path $Path -Value $Content -Verbose

但是,这不会代替$ oldCode。 我已经使用Write-Output来检查$ Content变量,并且它没有替换字符串,所以我假设这是匹配字符串或replace命令本身的问题,而不是Set-Content命令的问题。

关于如何使它工作的任何想法?

所以最后,我使用了以下内容。 这不是唯一的选项,您也可以使用API​​来构造元素。

$xmlPath = "c:\windows\system32\inetsrv\config\applicationHost.config"

[xml]$xml = Get-Content -Path $xmlPath

[xml]$xFrameXml = @"
            <customHeaders>
                <add name="X-Frame-Options" value="SAMEORIGIN" />
            </customHeaders>
"@

foreach($node in $xml.SelectNodes('/configuration/system.webServer/httpProtocol/customHeaders')){
    $node.ParentNode.AppendChild($xml.ImportNode($xFrameXml.customHeaders, $true));
    $node.ParentNode.RemoveChild($node);

}
$xml.Save($xmlPath);

您也许也可以使用.ReplaceChild但是我还没有找到正确的语法,所以如果有人这样做,它可能会更干净。

感谢Ansgar为我指出正确的方向。

暂无
暂无

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

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