随机查找XML属性

时间:2015-03-28 12:02:12

标签: xml powershell xpathnavigator select-xml

如何随机找到2个属性$_.CompleteName$_.Channel

+ $channel | ? {$liste} | get-random <<<<  -min 0 -max $liste.list.groupe.count
    + CategoryInfo          : InvalidArgument: (position:PSObject) [Get-Random 
   ], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Command 
   s.GetRandomCommand

示例数据

$Xliste = [xml]@"
<list>
   <groupe>
        <position type="General">
            <CompleteName>folder-1</CompleteName>
            <dateYY>2014</dateYY>
            <dateMM>jaenner</dateMM>
            <dateDD>mittwoch</dateDD>
            <Overall_mode>cbr</Overall_mode>
            <Duration>00:1:27</Duration>
            <Overall_rate>96.0Kbps</Overall_rate>
        </position>
        <position type="Version">
            <Channel>channel2</Channel>
            <CodecID>55</CodecID>
            <Duration>00:1:27</Duration>
            <Compression>Lossy</Compression>
            <StreamSize>96.0Kbps</StreamSize>
        </position>
    </groupe>
    <groupe>
        <position type="General">
            <CompleteName>folder-2</CompleteName>
            <dateYY>2013</dateYY>
            <dateMM>maerz</dateMM>
            <dateDD>montag</dateDD>
            <Overall_mode>cbr</Overall_mode>
            <Duration>00:8:12</Duration>
            <Overall_rate>96.0Kbps</Overall_rate>
        </position>
        <position type="Version">
            <Channel>channel1</Channel>
            <CodecID>49</CodecID>
            <Duration>00:8:12</Duration>
            <Compression>Lossy</Compression>
            <StreamSize>96.0Kbps</StreamSize>
        </position>
    </groupe>
</list>
"@

代码

$channel_and_CompleteName = Select-Xml $liste -xpath "*/*/*" | Select-Object -Expand node | ? {$_ -ne ($_.CompleteName)+" "+($_.Channel)}
$channel_and_CompleteName | ? {$liste} | get-random -min 0 -max $liste.list.groupe.count

1 个答案:

答案 0 :(得分:0)

仍然不清楚您在寻找什么,但这将采用该XML并随机选择ChannelCompleteName配对之一作为自定义对象

$Xliste.List.groupe | ForEach-Object{
    $props = @{}
    $_.Position | ForEach-Object{    
        If($_.Type -eq "General"){
            $props.CompleteName =  $_.CompleteName
        } ElseIf($_.Type -eq "Version"){
            $props.Channel =  $_.Channel
        }
    }
    New-Object -TypeName PSCustomObject -Property $props 
} | Get-Random

示例输出

CompleteName Channel 
------------ ------- 
folder-1     channel2

基于纯字符串的输出

$Xliste.List.groupe | ForEach-Object{
    $string = @()
    $_.Position | ForEach-Object{    
        If($_.Type -eq "General"){
            $string +=  $_.CompleteName
        } ElseIf($_.Type -eq "Version"){
            $string +=  $_.Channel
        }
    }
    $string -join "`t"
} | Get-Random 

<强>输出

folder-2    channel1