powershell对txt文件中的服务器列表进行ping操作,每行一个IP地址进行处理。处理几百台服务器需要注意性能优化,以避免长时间运行。
$stopWatch = [system.diagnostics.stopwatch]::startNew()$Location = "d:\\" + $PSScriptRoot$folderName = "ping"$folderPath = $Location + "\" + $folderNameIf((Test-Path $folderPath) -eq $False) { Write-Host "创建文件夹..." New-Item -path $Location -name $folderName -itemType "directory"}$pingFileName = "ok.txt"$pingFilePath = $folderPath + "\" + $pingFileNameIf((Test-Path $pingFilePath) -eq $False) { Write-Host "创建ping通文件..." New-Item -path $folderPath -name $pingFileName -itemType "File"}$nopingFileName = "no.txt"$nopingFilePath = $folderPath + "\" + $nopingFileNameIf((Test-Path $nopingFilePath) -eq $False) { Write-Host "创建ping不通文件..." New-Item -path $folderPath -name $nopingFileName -itemType "File"}$computerObjects = Get-Content C:\DNS.txt$totalCount = $computerObjects.count$sContent = "一共有:" + $totalCount.ToString() + "台服务器需要处理!"Write-Host $sContent -ForegroundColor Green$successCount = 0$failCount = 0ForEach($computerObject in $computerObjects) { try { if (Test-Connection $computerObject -Count 1 -ea 0 -Quiet) { $pingOK = "ping通" + $computerObject.ToString() Write-Host $pingOK -ForegroundColor Green Add-Content -Path $pingFilePath -Value $computerObject $successCount++ } else { $pingNO = "ping不通" + $computerObject.ToString() Write-Host $pingNO -ForegroundColor Red Add-Content -Path $nopingFilePath -Value $computerObject $failCount++ } } catch { $errMsg = "ping过程中出现错误:" + $computerObject.ToString() Write-Host $errMsg -ForegroundColor Blue Add-Content -Path $nopingFilePath -Value $computerObject $failCount++ }}$stopWatch.Stop()$totalseconds = $stopWatch.Elapsed.TotalSeconds$tooltip = "处理完毕,一共花费" + $totalseconds.ToString() + "秒"Write-Host $tooltip -ForegroundColor Red
转载于:https://www.cnblogs.com/love007/p/5126605.html