Pass Variable of System Names to New-PSSession

I’m trying the following to get the VM host of several remote systems:

$Systems = Get-Content systems.txt
$CommaDelimitedSystemsList = $Systems -join ","
$Sessions = New-PSSession -cn $CommaDelimitedSystemsList -cred UsernameHere
Invoke-Command -Session $Sessions -ScriptBlock {(get-item "HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters").GetValue("HostName")} 

Everything works fine if If I type out the comma delimited list.

However, when I use the variable $CommaDelimitedSystemsList, I get the error “New-PSSession : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings.”

The values are getting stored correctly in $CommaDelimitedSystemsList, so I’m not sure what the problem is.

Any ideas?

Try just -ComputerName $Systems . You want to be passing an array of computer names to that parameter, not a single comma-delimited string. (When you type it out yourself, assuming that you haven’t put the whole thing in quotes, the commas act as an operator in PowerShell that create an array.)

I thought that’s what I tried initially and checking here made me think it needed a comma delimited string.

However, looks like this works!

$Systems = Get-Content systems.txt
$Sessions = New-PSSession -cn $Systems -cred UsernameHere
Invoke-Command -Session $Sessions -ScriptBlock {(get-item "HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters").GetValue("HostName")}

Frustrating because I could have sworn I tried that first, but relieved since it works the way I thought it should.

Thanks for your help.