Pass multiple server names to New-PSSession through variable

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 {
    <Command>
}
Get-PSSession | Remove-PSSession

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.