Stopping services in order and restarting in reverse order

Hi,

I’m creating a script to handle moving a database and a file tree from a live server to a test server.

One of the things that needs to happen on the test server is for a number of services to be stopped in specific order before the running database is dumped and then restart them in reverse order.
My first thought was that I should just pop the service names in an array and run a foreach with Stop-Service. But I think I heard somewhere that you can’t be sure that POSH will run an array in the same order that you entered the items. Also I would have to reverse the order once I need to restart the services.
I’m aware that I can just do one line for each service but I’d really prefer to just have the service names in one location rather than in both the Stop-Service and Start-Service function.
Is a hash table a better idea for dealing with items in a specific order?
And what’s the best way of reversing the order for the Start-Service function?

Kind regards
/Laage

I think an array would be a perfect candidate. You could reverse it

$array = 'one','two','three','four','five'

$array

[array]::Reverse($array)

$array

image

Or do for loops

$array = 'one','two','three','four','five'

for($i = 0; $i -lt $array.count; $i++){
    $array[$i]
}

for($i = $array.count; $i -ge 0; $i--){
    $array[$i]
}

image

Or a foreach-object

$array = 'one','two','three','four','five'

0..$array.count | ForEach-Object {
    $array[$_]
}

$array.count..0 | ForEach-Object {
    $array[$_]
}

image

And just to solidify that whatever order the services are put into the array will be exactly the opposite when reversed.

$array = 1..10 | ForEach-Object -Parallel {Start-Sleep -Seconds (Get-Random -Maximum 2);$_}

$array

[array]::Reverse($array)

$array

1 Like

Thank you.
I’m not sure where I heard that arrays could be jumbled in use, but it apparently stuck. It seems that I can discount that and just go with my original plan.
And thank you also for a couple of easy ways of reversing the operation.

Kind regards
/Laage

It’s probably hashtables you are thinking of. You can’t control the order of them unless you type cast with [ordered]

Thank you, that might very well be it… Which makes it ironic that I thought that hashtables could be my solution to this. :smiley: