Using Out-GridView with -PassThru parameter to select multiple objects

If you were wondering how to select multiple objects from pop-up window using PowerShell then this post might be interesting for you 🙂

I would like to show you how you can easily select your servers with Out-GridView command. In this example I’ve created simple script where you can choose multiple servers for example for post patching reboots. On the beginning I added some short title:

When you press enter new window will open with server list gathered from the input file (CSV Format). Hold CTRL button if you want to select more than one machine:

Next you will be asked for confirmation:


Write-Host "`n-----------------------------------------------------------------------------------------`n"
Write-Host "                   Reboot Script: Please select servers from the list"
Write-Host "`n-----------------------------------------------------------------------------------------`n"
 pause
Write-Host " "


# Input file in CSV format
$Servers = (Import-Csv C:\temp\servers.csv )

# Opening new window to select servers
$Servernames = $Servers | Out-GridView -Title  "Choose servers" -PassThru 

    # If servers have not been selected write warning in host
    If ( !$Servernames )
    {
        Write-Warning "Servers have not been selected"
    }
    Else
    {
        # Display server names and their IP addresses
        Write-Warning "The following servers have been selected:"

        $Servernames | ft -wrap -auto

        # Confirm if you want to proceed
        Write-Host -nonewline "Do you want to proceed? (Y/N): "
        $Response = Read-Host
        Write-Host " "

            # If response was different that Y script will end
            If ( $Response -ne "Y" )
            { 
                Write-Warning "Script ends"       
            }
            Else
            {
                # Servers loop
                ForEach($Server in $Servernames."Server name")
                {
                    # Restart command
                    Write-Warning "Rebooting $Server :"
                    Restart-Computer -ComputerName $Server -Force -Wait -For PowerShell -Delay 10  -ErrorAction SilentlyContinue
                }
            }
    }

Script:
server-reboot

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.