По сути, у меня есть массив $ServerList
, который содержит список массивов, которые я хочу протестировать, в то время как $ExclusionList
- это список серверов, которые необходимо исключить.
Код должен тестировать списоксервера с Test-Connection
и сохраните недоступные в $nonactivearray
и удалите их из $ServerList
.После этого он удалит любую запись в $ExclusionList
из $ServerList
.
Если $ServerList
станет пустым массивом, он попросит пользователя ввести список серверов.
Кажется, код работает правильно, пока не будет указан правильный сервер.Я обнаружил, что, хотя $nonactivearray
становится пустым, $nonactivearray.Count
или $nonactivearray.Length
возвращают 1
, следовательно, он будет входить в бесконечный цикл, так как оба элемента $ServerList
и $nonactivearray
имеют число элементов больше 0
.
# Define function to center the text in the current line (taken from: https://stackoverflow.com/a/48622585/10516690)
function Write-HostCenter {
param($Message)
Write-Host ("{0}{1}" -f (' ' * (([Math]::Max(0, $Host.UI.RawUI.BufferSize.Width / 2) - [Math]::Floor($Message.Length / 2)))), $Message)
}
# Define Test-Connection as a string for Invoke-Expression later
[string]$TestConn = "Test-Connection -Quiet -Count 1 -ComputerName "
# Define excluded servers
$ExclusionList = @("Server1","Server2","Server3")
# Save old progress settings
$OldProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
# Test Server availability
$nonactivearray = @() # Array of unreachable/excluded servers
$nonactive = "" # String to display the unreachable/excluded doscovered in our list of servers. Probably unnecessary, "$nonactivearray" can be used
$i = 0
foreach ($newserver in $ServerList) {
if (-Not (Invoke-Expression -Command "$TestConn $newserver")) {
$nonactive += $newserver
$nonactivearray += $newserver
if ($i -lt $ServerList.Length) {
$nonactive += " "
}
}
$i++
}
$ProgressPreference = $OldProgress
# List unreachable and excluded servers
$nonactivearray += (Compare-Object -ReferenceObject $ServerList `
-DifferenceObject $ExclusionList `
-ExcludeDifferent -IncludeEqual).InputObject
$nonactive = "$nonactivearray"
$CurPosPing = $host.UI.RawUI.CursorPosition
while ($nonactivearray.Length -ge 1) {
$host.UI.RawUI.CursorPosition = $CurPosPing
Write-Host " These HOSTS are not reachable, hence they will be ignored:"
$TempForegroundColor = $Host.Ui.RawUI.ForegroundColor # <== Temporary solution
$Host.Ui.RawUI.ForegroundColor = "Red" # <== Temporary solution
Write-HostCenter $nonactive # Write-HostCenter defined in a function. It centers the text in the shell
$Host.Ui.RawUI.ForegroundColor = $TempForegroundColor # <== Temporary solution
# Remove unreachable servers with filters
$ServerList = $ServerList | Where-Object {$nonactivearray -notcontains $_}
# Check if the new list is empty
while ($ServerList.Length -lt 1) {
Write-Host " "
$CurPos = $host.UI.RawUI.CursorPosition
Write-Host " The list of server is now empty, please type it now. " -ForegroundColor Yellow
Write-Host " Use the comma `"" -NoNewline; Write-Host "," -NoNewline -ForegroundColor Yellow
Write-Host "`" as a separator (spaces will be ignored)."
Write-Host " "
# Get list from user
# $CurPos = $host.UI.RawUI.CursorPosition
$ServerList = Read-Host -Prompt " Server list"
$ServerList = $ServerList -replace ' ',''
[string[]]$ServerList = $ServerList -split ','
$ServerList = $ServerList | Where-Object {$_.length -gt 0}
while ($ServerList.Length -lt 1) {
$Host.UI.RawUI.CursorPosition = $CurPos
Write-Host " >>> The list is STILL empty, please type it again. <<< " -ForegroundColor Yellow
Write-Host " "
Write-Host " "
# $CurPos = $host.UI.RawUI.CursorPosition
$ServerList = Read-Host -Prompt " Server list"
$ServerList = $ServerList -replace ' ', ''
[string[]]$ServerList = $ServerList -split ','
$ServerList = $ServerList | Where-Object {$_.length -gt 0}
}
}
# Re-check server connectivity
$OldProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
Write-Host "serverlist"
$ServerList
$nonactivearray = @()
$nonactive = ""
$i = 0
foreach ($newserver in $ServerList) {
if (-Not (Invoke-Expression -Command "$TestConn $newserver")) {
$nonactive += $newserver
$nonactivearray += $newserver
if ($i -lt $ServerList.Length) {
$nonactive += " "
}
}
$i++
}
$ProgressPreference = $OldProgress
$nonactivearray += (Compare-Object -ReferenceObject $ServerList `
-DifferenceObject $ExclusionList `
-ExcludeDifferent -IncludeEqual).InputObject
$nonactive = "$nonactivearray"
}
Спасибо и всего наилучшего.
[EDIT]
Извините, я также забыл следующие строки, которые я добавил в верхней части кода:
# Define function to center the text in the current line (taken from: https://stackoverflow.com/a/48622585/10516690)
function Write-HostCenter {
param($Message)
Write-Host ("{0}{1}" -f (' ' * (([Math]::Max(0, $Host.UI.RawUI.BufferSize.Width / 2) - [Math]::Floor($Message.Length / 2)))), $Message)
}
# Define Test-Connection as a string for Invoke-Expression later
[string]$TestConn = "Test-Connection -Quiet -Count 1 -ComputerName "
# Define excluded servers
$ExclusionList = @("Server1","Server2","Server3")
Надеюсь, я больше ничего не забуду ...