Pass multiple server names to New-PSSession through variable

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 3 years ago.

  • Author
    Posts
  • #14701
    Profile photo of Matt McElreath
    Matt McElreath
    Participant

    I want to be able to invoke a command on a set of servers that the user specifies. This could be 1 server or it could be many. Here is what I was thinking of doing but it doesnt work. Does anyone have any thoughts?

    
    $cred = Get-Credential
    $server = Read-Host "Please enter the servers:"
    $sessions = New-PSSession -ComputerName $server -Credential $cred
    Invoke-Command -Session $sessions {
        
    }
    Get-PSSession | Remove-PSSession
    
  • #14702
    Profile photo of Don Jones
    Don Jones
    Keymaster

    That's because you're prompting by using Read-Host. That only takes a single value.


    [CmdletBinding()]
    param(
    [Parameter(Mandatory=$True)]
    [string[]]$ComputerName
    )

    With that at the top of a script or function, PowerShell will handle the prompting, and it'll prompt for multiple values. You hit Enter on a blank to continue, and $ComputerName would be an array of computer names. That could be passed directly to the -ComputerName parameter of New-PSSession.

    Now, alternately, I supposed you could

    $in = Read-Host "Enter comma-separated computer list"
    $computers = $in -split ','

    And $computers would contain the needed array of strings. But I prefer to let PowerShell do the heavy lifting – it's better at it.

You must be logged in to reply to this topic.