简体   繁体   English

PowerShell:确认连接到服务器并选择继续脚本

[英]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 | -write-output section is wrong but its there to kind of show what I'm wanting. | -write-output部分是错误的,但它在那里显示了我想要的东西。


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假设 $Servers 是一个服务器名称数组

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.我从来没有真正喜欢过Test-Connection的想法,它是一种声明系统可以在回显请求收到回显回复时运行命令的方法。 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).如果可以建立 session,请询问您是否要继续(可以很容易地将其修改为在catch块中)。 If a session cant be established, handle it appropriately and see why its couldnt be established.如果 session 无法建立,请适当处理,看看为什么无法建立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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