简体   繁体   中英

PowerShell: Confirming Connection to Servers and choosing to continue script

Good Afternoon,

I'm working on a small line of code to have run at the beginning on a script to test the connection to my servers giving the option to continue running the script if some connections cannot be made. I'm having some troubles sorting out how it should be formatted. NOTE: I do know the | -write-output | -write-output section is wrong but its there to kind of show what I'm wanting.


Foreach ($Server in $Servers){
    if(Test-Connection $Server -count 2 -Quiet) {
        write-host "$server is available" -foregroundcolor green
        } else { 
            write-host "$server cannot be reached" -foregroundcolor Red | Write-output $noconnection
                    }
    }

If ($noconnection -eq $true) {$continue = read-host "A connection couldn't be made to all the servers, do you wish to continue? [y/n]"}
If ($continue -eq "n") {Write-host "cancelling script"}

Although not sure what you mean exactly with "I'm having some troubles sorting out how it should be formatted." , I think it is about how to break out of the loop versus exiting the script altogether. Perhaps this is what you are after:

Assuming $Servers is an array of server names

foreach ($server in $Servers){
    if(Test-Connection $Server -Count 2 -Quiet) {
        Write-Host "$server is available" -ForegroundColor Green
    } 
    else { 
        Write-Host "$server cannot be reached" -ForegroundColor Red
        $continue = Read-Host "Server '$server' did not respond, do you wish to continue testing? [y/n]"
        if ($continue -eq "n") {
            Write-Host "Cancelling script"
            # if this foreach loop is the last part of the script
            # you can quit by just exiting the loop with
            # break

            # if there is more code following this part, break out of the script entirely using
            exit
        }
    }
}

I have never really liked the idea of Test-Connection as a means of declaring a system is good to run commands against if an echo request receives an echo reply. Your question is a little vague on what you're looking for as well but, a good approach is trying to establish sessions against it, as it's pretty much a guarantee the following commands will run.

Param(
    [Parameter(Mandatory=$false,
                ValueFromPipeLine=$true,
                ValueFromPipeLineByPropertyName=$true)]
    [Alias('cn','cc')]
    [String[]]$Servers = @('server1','server2','server3') )
Process{
    Foreach ($Server in $Servers){
        Try{
            $PSSession = New-PSSession -ComputerName $Server -ErrorAction Stop

            "Session to $Server established."

            $Confirm = Read-Host -Prompt "Would you like to continue?[Y/N]"
                if($Confirm.ToLower().TrimStart() -like "n*" -or $Confirm.ToLower() -like "q*"){Break} 
                elseif([String]::IsNullOrEmpty($Confirm.Trim()) -eq $true) { "Null string"; Break }

#Rest of the code here:
#Could also just point to another function that actually
#holds the actual code meant to be run, and this could be used
#as a means of just checking connectivity.


        
            } Catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
                "Unable to connect to PC: $Computer `nError: $($Error[0].Exception.Message.Split('.')[2].Trim())!"
                    $IP = Test-Connection -ComputerName $Computer -Count 1 -ErrorAction SilentlyContinue | 
                            Select-Object -ExpandProperty IPV4Address | 
                            Select-Object -ExpandProperty IPAddressToString
                                if($IP) { "IPAddress: $IP" }
                                    Else { "IPAddress: Unable to get IP." }
            
        }
    }
}

If a session could be established, ask if youd like to continue (which could be modified as easily to be in the catch block instead). If a session cant be established, handle it appropriately and see why its couldnt be established.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM