Powershell循环遍历群组

时间:2017-05-12 18:47:39

标签: powershell

我想单独循环遍历一组组的内容,即组1包含:

AppReadiness MessagingService_e88063 BthHFSrv

我想循环遍历该组并将其优先级添加到它看起来像这样:

AppReadiness - 1

等等。

这是我的代码:

function CallServices{

$VerbosePreference = 'Continue'

$ServiceGroups = Import-CSV "C:\Users\mwalters\Desktop\app-test.csv" | Group-Object Priority | Sort Name
#$ServiceGroups

 $ServiceGroups | ForEach-Object {
    "Stopping priority $($_.name) services.."
    "count groups-"
    $ServiceGroups.Count

    tester $ServiceGroups
   }
  }

function tester{
param(
    $ServiceGroups
)

$Applications = @()

ForEach ($ServiceGroup in $ServiceGroups){

    $ServiceGroup | ForEach-Object {

        $application = $_.Group.ApplicationName
        $Priority = $_.Group.Priority 
        $app = $application +"-"+$Priority
        $Applications += $app
    }
    '- - - - - - - - - - '
    $Applications

    $Applications = @()

   }



#$ServiceGroups
#"count within group-" 
#$ServiceGroups[0].count


}


CallServices

1 个答案:

答案 0 :(得分:1)

如果您想依次处理每个组,您可以这样做:

$ServiceGroups = Import-CSV "C:\Users\mwalters\Desktop\app-test.csv" | Group-Object Priority | Sort Name

$ServiceGroups | ForEach-Object {
    Write-Host "Priority $($_.name) services"

    $_.Group | ForEach-Object {
        "$($_.ApplicationName) - $($_.Priority)"
    }
}

或者只是一次性完成所有组,尽管这里的分组变得多余:

$ServiceGroups = Import-CSV "C:\Users\mwalters\Desktop\app-test.csv" | Group-Object Priority | Sort Name

$ServiceGroups.Group | ForEach-Object {
    "$($_.ApplicationName) - $($_.Priority)"
}

这将产生与上述相同的结果:

$ServiceGroups = Import-CSV "C:\Users\mwalters\Desktop\app-test.csv" | Sort Priority,Name

$ServiceGroups | ForEach-Object {
    "$($_.ApplicationName) - $($_.Priority)"
}