Reputation: 223
I have a CSV file as follows:
It contains a windows service and a priority and I want the priority to control the order n which the services start and stop.
I.e stop all priority 1 before priority 2 and so on until priority 9 which would be the last one. After stopping 1-9 in order I also want it to start in order.
Having trouble going about this. I don't want to have 9 different arrays in which I store the groups because it feels inefficient. Any thoughts or suggestions?
$Columns = "ApplicationName", "Priority"
$Applications = @()
$Path = "C:\Users\mwalters\Desktop\app-test.csv"
$CSV = Import-csv -Path $Path | Select $Columns
$Applications += $CSV | Sort -Property Priority
$AppsToLoopOver = @()
$i = 0
foreach ($Application in $Applications) {
$ApplicationFromCSV = $Applications.ApplicationName[$i]
$AppPriority = $Applications.Priority[$i]
$AppsToLoopOver += [PSCustomObject]@{
Priority=$AppPriority;
ApplicationName=$ApplicationFromCSV
}
$i++
}
$Group1 = @()
$Group2 = @()
$Group3 = @()
foreach ($Priority in $AppsToLoopOver.Priority) {
if ($Priority -eq 1) {
$Group1 += $Priority + " Group1"
} elseif ($Priority -eq 2) {
$Group2 += $Priority + " Group2"
} elseif($Priority -eq 3) {
$Group3 += $Priority + " Group3"
}
}
$AppsToLoopOver
Upvotes: 1
Views: 59
Reputation: 23355
You could just sort by priority, but if you specifically want to operate on them as groups, you could use the Group-Object
cmdlet such as in the following:
$VerbosePreference = 'Continue'
$ServiceGroups = Import-CSV "C:\Users\mwalters\Desktop\app-test.csv" | Group-Object Priority | Sort Name
$ServiceGroups | ForEach-Object {
Write-Verbose "Stopping priority $($_.name) services"
$_.Group | Select -ExpandProperty ApplicationName | Stop-Service -WhatIf
}
Remove -WhatIf
if you're happy with the outcome.
Upvotes: 1
Reputation: 200293
For grouping structured data use the Group-Object
cmdlet:
Import-Csv $Path |
Group-Object Priority |
Sort-Object {[int]$_.Name} |
ForEach-Object {
# ... do stuff ...
}
Upvotes: 2