How can I write Xml.linq in powershell?

I am trying to do this in powershell:

XDocument document = XDocument.Load(@"web.config"); var comments = document.Descendants("client").DescendantNodes().OfType<XComment>().ToArray(); foreach (var comment in comments) { XElement unCommented = XElement.Parse(comment.Value); comment.ReplaceWith(unCommented); } 

I tried something like this:

 $xDoc = [System.Xml.Linq.XDocument]::Load("web.config") [System.Collections.Generic.IEnumerable[System.Xml.Linq.XElement]] $enum = $xDoc.Descendants("client") $clients = [System.Xml.Linq.Extensions]::DescendantNodes($enum) 

But I get the error message "Exception calls DescendantNodes with 1 argument: value cannot be null"

+9
source share
2 answers

I got this to work (uncommenting something from an XML document) using linq in powershell:

  [Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq") | Out-Null $xDoc = [System.Xml.Linq.XDocument]::Load("web.config") $endpoints = $xDoc.Descendants("client") | foreach { $_.DescendantNodes()} $comments = $endpoints | Where-Object { $_.NodeType -eq [System.Xml.XmlNodeType]::Comment -and $_.Value -match "net.tcp://localhost:9876/RaceDayService" } $comments | foreach { $_.ReplaceWith([System.Xml.Linq.XElement]::Parse($_.Value)) } $xDoc.Save("web.config") 
+24
source

If you were writing Powerahell Modules , you would create a manifest file that would load the same dependencies when calling Import-Module MyModule :

 # Comma-separated assemblies that must be loaded prior to importing this module RequiredAssemblies = @("System.Xml.Linq") 

This is the recommended way for those who write modules.

+3
source

Source: https://habr.com/ru/post/1413512/


All Articles