Powershell脚本用于建立与远程服务器的连接

时间:2016-10-19 13:19:05

标签: powershell powershell-v2.0 powershell-remoting

我有一个要求,我必须测试与目标服务器的连接(由于网络问题,有时会出现连接)。

所以基本上,我需要检查一下,如果由于任何原因它发生故障,PowerShell脚本应该能够重新启动它。

我能够编写一个脚本来测试下面列出的目标服务器的连接。但是,当网络出现故障时,不知道如何重新建立连接。

任何人都可以帮我添加“建立连接”部分。

$servers = "server name"

Clear-Content c:\myprocesses.txt

foreach ($s in $servers) {
  if (!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -EA 0 -Quiet)) {
    "Problem connecting to $s"
    "Flushing DNS"
    ipconfig /flushdns | Out-Null

    "Registering DNS"
    ipconfig /registerdns | Out-Null

    "doing a NSLookup for $s"
    nslookup $s >> C:\myprocesses.txt
    "Re-pinging $s"

    if (!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -ea 0 -quiet)) {
      "Problem still exists in connecting to $s"
    } else {
      "Resolved problem connecting to $s"
    } # end if

    tracert $s >> c:\myprocesses.txt
  } else {
    Enable-PSRemoting -Force
    Restart-Service WinRM

    if (Test-Connection -ComputerName $s -Quiet) {
      New-PSSession $s
    }

    "No Problem connecting to $s"
    "Writing the Traceroute to the destination server $s"
    tracert $s >> c:\myprocesses.txt

    "c:\myprocesses.txt ready" 
  } # end if
} # end foreach`

0 个答案:

没有答案