[英]PowerShell: Confirming Connection to Servers and choosing to continue script
下午好,
我正在编写一小行代码以在脚本的开头运行以测试与我的服务器的连接,如果无法建立某些连接,则可以选择继续运行脚本。 我在整理它应该如何格式化时遇到了一些麻烦。 注意:我知道| -write-output
| -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"}
尽管不确定“我在整理应如何格式化时遇到了一些麻烦”的确切含义。 ,我认为这是关于如何跳出循环而不是完全退出脚本。 也许这就是你所追求的:
假设 $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
}
}
}
我从来没有真正喜欢过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." }
}
}
}
如果可以建立 session,请询问您是否要继续(可以很容易地将其修改为在catch
块中)。 如果 session 无法建立,请适当处理,看看为什么无法建立。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.