从XML值的子字符串添加其他列

时间:2016-12-08 19:20:10

标签: xml powershell

我正在尝试获取XML值(MacID)的子字符串,其中我只想要MacID的最后4位数字,我想将其添加为我正在导出的.csv的附加列。我如何从MacID中获取4个字符的子字符串?我希望我可以使用MacID.Substring(8,4),但这似乎不起作用。有什么想法吗?

以下是我引用的一些代码:

$serverName = Get-Content C:\Temp\MPOS\MPOSServer.txt
$xml = Get-Content C:\Temp\MPOS\DeviceConfig.xml
$xmldata = [xml]$xml
$MDATcsv = $xmldata.DeviceConfig.ChildNodes |
           Select @{Name="ServerName"; Expression={ $serverName }}, RegisterID, MacID |
           Export-Csv -Path D:\Reports\MPOS\MDATInfo.csv -NoTypeInformation -Append
$MDATcsv

这里有一些XML文件供参考:

<?xml version="1.0" encoding="utf-8"?>
<DeviceConfig>
    <Device RegisterID="1129" MacID="A4313596AEDD" />
    <Device RegisterID="1123" MacID="E425E7960663" />
    <Device RegisterID="1132" MacID="E425E7960666" />
    <Device RegisterID="1120" MacID="E425E796878A" />
    <Device RegisterID="1134" MacID="E425E7988992" />
    <Device RegisterID="1135" MacID="E425E798CBA6" />
    <Device RegisterID="1121" MacID="E425E79B3DD4" />
    <Device RegisterID="1127" MacID="E425E79BF845" />
    <Device RegisterID="1126" MacID="E425E79CD962" />
    <Device RegisterID="1112" MacID="E425E79DF316" />
</DeviceConfig>

1 个答案:

答案 0 :(得分:2)

bool应该有效,但您需要calculated property来添加另一个具有缩短值的列/字段,并且您需要从当前对象获取原始属性(Substring(8, 4)) :

$_.MacID

其他提取最后4个字符的方法是例如

... | Select-Object @{n="ServerName";e={$serverName}}, RegisterID, MacID,
                    @{n='Last';e={$_.MacID.Substring(8, 4)}} | Export-Csv ...

$_.MacID.Substring($_.MacID.Length - 4)
相关问题