How to get values in CDATA in XML file with PowerShell?

会有一股神秘感。 提交于 2019-12-06 05:08:25

The canonical way of storing data like that is a hashtable. Use the ConvertFrom-StringData cmdlet for transforming a list of key=value pairs in a string to a hashtable data structure. Since your data has colons instead of = you need to replace them first.

$cdata = @'
aggressorAllianceID: 99006227
aggressorCorpID: 244898283
aggressorID: 1283793762
armorValue: 1.0
hullValue: 1.0
moonID: 40043321
shieldValue: 0.5166110755741394
solarSystemID: 30000686
typeID: 20060
'@

$ht = $cdata -replace ':', '=' | ConvertFrom-StringData

Then you can access the individual values like this:

$ht['aggressorID']
$ht['hullValue']
...

Undeleted due to Tomalak's helpful comments - please read before considering New-Variable

Ansgar's answer is a better way to store this data and deal with this programmatically. To answer your literal question of how to get, for example $aggressorAllianceID = 99006227, you can use New-Variable

input.txt

aggressorAllianceID: 99006227
aggressorCorpID: 244898283
aggressorID: 1283793762
armorValue: 1.0
hullValue: 1.0
moonID: 40043321
shieldValue: 0.5166110755741394
solarSystemID: 30000686
typeID: 20060

$myReturnedValues = Get-content .\input.txt
foreach($line in $myReturnedValues){
    New-Variable -Name ($line.Split(": "))[0] -Value ($line.Split(": "))[2]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!