Pass multiple server names to New-PSSession through variable

Welcome Forums General PowerShell Q&A Pass multiple server names to New-PSSession through variable

This topic contains 1 reply, has 2 voices, and was last updated by

4 years, 10 months ago.

  • Author
  • #14701

    Points: 22
    Rank: Member

    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

    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

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


    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.

The topic ‘Pass multiple server names to New-PSSession through variable’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort