How do I make array of strings to pass to -computername parameter?


I need pass an array of strings to -ComputerName parameter of Restart-Service cmdlet
My computer names are just string with number appended to it. I tried following but it did not work (-ComputerName (1…10| % {“COMPUTERNAME$_”}) ). How do I elegantly do it inline?

Restart-Service doesn’t have a -ComputerName parameter, so far as I know. But assuming that you were using a cmdlet that did have such a parameter, the only problem I see with your post is that you’ve placed the whole thing into a set of parentheses. The argument should be in parens, but the parameter itself should not. For example:

Restart-Service -Name SomeService -ComputerName (1..10| % {"COMPUTERNAME$_"})

Unlike Restart-Service, Get-Service does have a -ComputerName parameter. I’m not sure if you’ll be able to pipe the resulting ServiceController objects into Restart-Service (depends on how it’s written; it may wind up trying to restart a service by the same name on the local computer), but if nothing else, you could do something like this:

Get-Service -Name SomeService -ComputerName (1..10| % {"COMPUTERNAME$_"}) |
ForEach-Object {
        if ($_.Status -ne 'Stopped' -and $_.Status -ne 'StopPending')

        $_.WaitForStatus('Stopped', (New-TimeSpan -Seconds 30))
        Write-Error -ErrorRecord $_

Thanks. All is working now.

You’ve removed the double quotation marks around “COMPUTERNAME$_”, by the looks of it. They’re important.

Yes, thanks that was the issue.