0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellでリストのIPアドレスに対して繰り返し到達性を確認する

Last updated at Posted at 2022-06-24

Whileを使かって繰り返しIPアドレスリストへのIP到達性を確認する

IP到達性を確認したいIPアドレスのリストを作成し、そのリストに対して繰り返しTest-Connectionを使ったICMPのチェックを実施します。

ユースケースのポイント

  • foreachを使ってリストからIPアドレスを読み込み変数に代入する
  • 上記のforeachを使ったリストの1巡を、whileを使って管理する
    ※Pingを実施する全回数、もしくは「成功」「失敗」の回数で実行回数を管理する

以下、環境です。
Windows 10 Enterprise
PowerShell 5.1 

※デフォルトの環境で使えることを意識しているのでPowerShell 7を使っていません。

ipAddrList.txt
172.22.1.201
172.22.1.170
172.22.1.81
172.22.1.26
172.22.1.25
172.22.0.1
172.22.0.2
  • IP到達性を確認したいIPアドレスリスト
icmpTesp.ps1
$ipAddrs = (Get-Content ./ipAddrList.txt)

$i = 0
while ($i -lt 2){
    foreach ($line in $ipAddrs) {
        $result = Test-Connection $line -Count 1 -Quiet
        if ($result -eq "True") {
            Write-Host $line "Reachable!"
            #$i++
        } else {
            Write-Host $line "Warning : Unreachable!"
            $i++
        }
    }
}
  • 2回「失敗」するとスクリプトが終了します。
PS C:\Users\MashCannu> .\icmpTest.ps1
172.22.1.201 Reachable!
172.22.1.170 Reachable!
172.22.1.81 Reachable!
172.22.1.26 Reachable!
172.22.1.25 Reachable!
172.22.0.1 Reachable!
172.22.0.2 Warning : Unreachable!
172.22.1.201 Reachable!
172.22.1.170 Reachable!
172.22.1.81 Reachable!
172.22.1.26 Reachable!
172.22.1.25 Reachable!
172.22.0.1 Reachable!
172.22.0.2 Warning : Unreachable!

コード解説

line1.ps1
$ipAddrs = (Get-Content ./ipAddrList.txt)
  • $ipAddrListを読み込み変数ipAddrsに代入する
line2.ps1
    foreach ($line in $ipAddrs) {
        $result = Test-Connection $line -Count 1 -Quiet
        if ($result -eq "True") {
            Write-Host $line "Reachable!"
            #$i++
        } else {
            Write-Host $line "Warning : Unreachable!"
            $i++
  • $ipAddrsから1行づつIPアドレスを読み込み変数 $lineに代入
  • Test-Connectionで対象のIPアドレス $line に対して1回pingを実施し結果をBoolen値 True/Falseで返す
  • Falseの場合(else{}ブロック)は$i++ を付け、1つずつ増やして終了する回数をカウントする
line3.ps1
$i = 0
while ($i -lt 2){

}
  • $i = 0 初期値をゼロで設定
  • ($i -lt 2) で -lt (less than) 2回以下と条件設定
  • Foreachブロック内で、$i++で1つづ増やして回数をカウントしている
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?