使用Powershell,取消注释配置文件中的一行

时间:2016-04-20 16:19:05

标签: xml powershell config session-state

我在配置文件中注释了两个会话状态节点。如何使用Powershell仅取消注释第一个会话状态节点?

<configuration>
 <system.web>
  <!--<sessionState allowCustomSqlDatabase="true" mode="SQLServer" sqlCommandTimeout="150" sqlConnectionString="SessionConnectionString"></sessionState>-->
  <!--sessionState mode="InProc" timeout="500"></sessionState-->
 </system.web>
</configuration>

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式

(gc settings.xml -Raw) -replace "<!--(.+?)-->",'$1'

在某些边缘情况下,这可能会出现问题,在这种情况下,您可以通过以下代码获取XML注释:

([xml](gc settings.xml)).configuration.'system.web'.'#comment'

然后你可以AppendChild()从注释字符串构建xml节点。

答案 1 :(得分:0)

简单方法:使用正则表达式进行文本操作。在要取消注释的行中查找唯一的内容。例如:

#Get-Content is in ( ) to read the whole file first so we don't get file in use-error when writing to it later
(Get-Content -Path web.config) -replace '<!--(<sessionState allowCustomSqlDatabase.+?)-->', '$1' | Set-Content -Path web.config

Demo @ Regex101

艰难的方式:Xml操作。我已经在这里发表了第一条评论,但如果情况更好,您可以像上面一样轻松搜索特定节点:

$fullpath = Resolve-Path .\config.xml | % { $_.Path }
$xml = [xml](Get-Content $fullpath)

#Find first comment
$commentnode = $xml.configuration.'system.web'.ChildNodes | Where-Object { $_.NodeType -eq 'Comment' } | Select-Object -First 1
#Create xmlreader for comment-xml
$commentReader = [System.Xml.XmlReader]::Create((New-Object System.IO.StringReader $commentnode.Value))
#Create node from comment
$newnode = $xml.ReadNode($commentReader)
#Replace comment with xmlnode
$xml.configuration.'system.web'.ReplaceChild($newnode, $commentnode) | Out-Null
#Close xmlreader
$commentReader.Close()

#Save xml
$xml.Save($fullpath)
相关问题