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

时间:2021-05-11 17:14:23

标签: powershell server connection windows-server-2012-r2

下午好,

我正在编写一小行代码,在脚本的开头运行以测试与我的服务器的连接,如果无法建立某些连接,则可以选择继续运行脚本。我在整理它的格式时遇到了一些麻烦。 注意:我确实知道 | -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"}

2 个答案:

答案 0 :(得分:2)

虽然不确定您对 的确切含义是什么“我在整理它的格式时遇到了一些麻烦。”, 我认为这是关于如何跳出循环而不是完全退出脚本。也许这就是您所追求的:

假设 $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
        }
    }
}

答案 1 :(得分:0)

我从来没有真正喜欢 Test-Connection 的想法,作为声明系统可以在回显请求收到回显回复时对其运行命令的好方法。 您的问题对于您正在寻找的内容也有点含糊,但是,尝试建立针对它的会话是一个很好的方法,因为它几乎可以保证以下命令将运行。

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." }
            
        }
    }
}

如果可以建立会话,请询问您是否要继续(可以很容易地将其修改为在 catch 块中)。如果无法建立会话,请妥善处理并查看无法建立的原因。