使用PowerShell,取消注解配置文件中的一行

vaqhlq81  于 2023-11-18  发布在  Shell
关注(0)|答案(2)|浏览(154)

我在配置文件中注解了两个Session State节点。如何使用PowerShell仅取消注解第一个Session State节点?

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

字符串

4xy9mtcn

4xy9mtcn1#

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

# 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)

1cosmwyk

1cosmwyk2#

你可以使用正则表达式来实现

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

字符串
这在某些边缘情况下可能会有问题,在这种情况下,您可以通过以下代码获得XML注解:

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


然后你可以AppendChild()到适当的地方从注解字符串构造xml节点。

相关问题