Importing XML String with Powershell variables

by mk.maddin at 2013-03-15 12:03:26

Hey community,

With $xml = ([xml](Get-Content -LiteralPath "C] i am importing an xml like this:

But when i give out $xml i don’t get “C:\USERS\MYUSERNAME\testpath” what i get is “$env:USERPROFILE\testpath”.

How can i get powershell to interpret the given variables?

Thank you for help

by DonJ at 2013-03-15 12:08:41
&$var will execute what’s in $var.
by mk.maddin at 2013-03-16 01:40:52
Hey DonJ,

Thanks for your reply.
But i can’t get it work.
using $xml = ([xml](Get-Content -LiteralPath “C:\anypath\config.xml”)).Xml

together with:

I’m getting Error:
Cannot convert value “System.Object[]” to type “System.Xml.XmlDocument”. Error: "An error occurred while parsing EntityName.
Line 2, position 11."
At C:\anypath\Untitled1.ps1:1 char:1
+ $xml = ([xml](Get-Content -LiteralPath “C:\anypath\config.xml”)).Xml
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:slight_smile: [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastToXmlDocument

Using $xml = ([xml](Get-Content -LiteralPath “C:\anypath\config.xml”)).Xml

together with:

I’m getting Error:
& : The term ‘$env:USERPROFILE\testpath’ is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\anypath\Untitled1.ps1:2 char:2
+ &$xml.path
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ($env:USERPROFILE\testpath:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

What am I doing wrong?
by DonJ at 2013-03-16 08:07:18
Part of the problem is that you’re overthinking it. Load the XML like this:

[xml]$xml = Get-Content filename.xml

You don’t need all that other stuff. Second, if you manually just try $xml.path, you’ll see that it doesn’t return anything. $xml represents the document. Under that, you have an <xml> node, then <path>. So it’s $xml.xml.path to get to it.

Third, the second error you’re getting is because & evaluates the string, and the <path> you provide is not a path - it’s a variable. ENV: would be the start of a path; $env is a variable. They both go to the same place, but the shell treats them differently. You need to expand the string:

PS C:&gt; $ExecutionContext.InvokeCommand.ExpandString($xml.xml.path)