title: How to cast all XML files as XML objects?
body: <p>How can we use PowerShell to cast multiple XML files to objects?</p>
  
  <p>Suppose we have a directory of XML files</p>
  
  <pre class="lang-bsh prettyprint-override"><code>$xmlfiles = Get-ChildItem C:\Directory -Filter *.xml
  
  foreach ($file in $xmlfiles) {
    [xml]$file Get-Content $_
  }
  </code></pre>
  
  <p>I am not sure how to proceed - if we want to query each file as it passes, do we need a nested <code>foreach</code>?</p>
  
  <p>I am only casting as XML to make simple queries across multiple documents.
  All of my documents have identical schema and I want to select a consistent set of nodes and attributes from every document.</p>
  
  <p>I have tried as suggested in the comments</p>
  
  <pre class="lang-bsh prettyprint-override"><code>foreach ($file in $xmlfiles) {
    Select-Xml $file -Xpath "//node2"
  }
  </code></pre>
  
  <p>but I get a runtime exception:</p>
  
  <pre>Cannot convert value "sample-document.xml" to type "System.Xml.XmlDocument". Error:
  "The specified node cannot be inserted as the valid child of this node, because the
  specified node is the  wrong type."
  At line:1 char:10
  + foreach ($file in $xmlfiles) {
  +          ~~~~~
      + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
      + FullyQualifiedErrorId : RuntimeException</pre>