简体   繁体   中英

Powershell Xml Attribute cast to concrete datatype

I have the below simple xml file

<?xml version="1.0" encoding="utf-8"?>
<MyRoot
  MyGuid="99999999-9999-9999-9999-999999999999"
  >
</MyRoot>

and code

    [xml]$xml = Get-Content "C:\myfile.xml"

    $unTypeVariable = $xml.MyRoot | Select MyGuid   

    Write-Host "unTypeVariable = '$unTypeVariable'"

    [GUID]guidValue = [GUID]($unTypeVariable)

third line output:

unTypeVariable = '@{MyGuid=99999999-9999-9999-9999-999999999999}'

On the last line, I keep getting a cast exception (immediately below). I understand it, but I don't know how to resolve it.

Cannot convert the "@{MyGuid=99999999-9999-9999-9999-999999999999}" value of type "Selected.System.Xml.XmlElement" to type "System.Guid".

I've tried:

    [GUID]guidValue = [GUID]($unTypeVariable.Text)

    [GUID]guidValue = [GUID]($unTypeVariable.Value)

    [GUID]guidValue = [GUID]($unTypeVariable.InnerText)

    [GUID]guidValue = [GUID]($unTypeVariable.'#text')

It's probably something stupid.

I'm not a powershell guru.

I finally got it with

$unTypeVariable = $xml.SelectSingleNode('//MyRoot').Attributes["MyGuid"].Value

[GUID]guidValue = [GUID]($unTypeVariable)

And a coworker just sent me a message.

This will work too:

$unTypeVariable = $xml.MyRoot.MyGuid

[GUID]guidValue = [GUID]($unTypeVariable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM