Author Posts

September 25, 2014 at 10:58 am

Hello,

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?

September 25, 2014 at 11:08 am

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 {
    try
    {
        if ($_.Status -ne 'Stopped' -and $_.Status -ne 'StopPending')
        {
            $_.Stop()
        }

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

September 25, 2014 at 11:26 am

Thanks. All is working now.

September 25, 2014 at 11:28 am

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

September 25, 2014 at 11:32 am

Yes, thanks that was the issue.