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

Welcome Forums General PowerShell Q&A 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

GS
 
Participant
4 years, 2 months ago.

  • Author
    Posts
  • #19102
    GS

    Participant
    Points: 1
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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
    GS

    Participant
    Points: 1
    Rank: Member

    Thanks. All is working now.

  • #19105

    Member
    Points: 0
    Rank: Member

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

  • #19106
    GS

    Participant
    Points: 1
    Rank: Member

    Yes, thanks that was the issue.

The topic ‘How do I make array of strings to pass to -computername parameter?’ is closed to new replies.