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

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of GS GS 2 years, 2 months ago.

  • Author
    Posts
  • #19102
    Profile photo of GS
    GS
    Participant

    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?

  • #19103
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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 $_
        }
    }
    
  • #19104
    Profile photo of GS
    GS
    Participant

    Thanks. All is working now.

  • #19105
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

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

  • #19106
    Profile photo of GS
    GS
    Participant

    Yes, thanks that was the issue.

You must be logged in to reply to this topic.