gpt4 book ai didi

powershell - 使用 Powershell 对 XML 进行排序

转载 作者:行者123 更新时间:2023-12-03 09:59:43 25 4
gpt4 key购买 nike

所以我有一些 XML,我要在其上创建一个集合,然后尝试根据元素对其进行排序,但它不起作用。

我的代码

$xml = [xml](Get-Content $args)

function readServersfromXML ( ) {

$xml.Settings.Server | select -ExpandProperty Name
}

function readServerServicesfromXML ( $server ) {
$xml.Settings.Server | Where-Object {$_.Name -eq $server} | Select-Object -ExpandProperty Services
}

function getServerServiceStatus ( $servers ) {

foreach ( $server in $servers ) {
$services = ( readServerServicesfromXML $server )
foreach ( $service in $services.ChildNodes ) {
$service | Sort-Object StartOrder
}
}
}

$servers = readServersfromXML
getServerServiceStatus ( $servers )

XML

<?xml version="1.0"?>
<Settings>
<Server>
<Name>Server1</Name>
<StartOrder>1</StartOrder>
<Services>
<Service>
<Name>Service1</Name>
<StartOrder>1</StartOrder>
</Service>
<Service>
<Name>Service2</Name>
<StartOrder>2</StartOrder>
</Service>
<Service>
<Name>Service4</Name>
<StartOrder>4</StartOrder>
</Service>
<Service>
<Name>Service3</Name>
<StartOrder>3</StartOrder>
</Service>
</Services>
</Server>
</Settings>

我希望输出是这样的

Name                                                        StartOrder
---- ----------
Service1 1
Service2 2
Service3 3
Service4 4

我不断得到的输出是这样的:

Name                                                        StartOrder
---- ----------
Service1 1
Service2 2
Service4 4
Service3 3

有人有想法吗?我试过将 StartOrder 转换为 [int] 但这也不起作用。提供任何帮助。

最佳答案

此函数的修改版本按 StartOrder 升序排序:

function getServerServiceStatus ( $servers ) 
{
foreach ( $server in $servers )
{
$services = ( readServerServicesfromXML $server )
$services.ChildNodes | Sort-Object { [int] $_.StartOrder}
}
}

输出是:

Name                                                        StartOrder
---- ----------
Service1 1
Service2 2
Service3 3
Service4 4

关于powershell - 使用 Powershell 对 XML 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33510035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com