WindowsPowerShell

PowerShellのネットワーク操作【Test-Connection・Invoke-WebRequest・REST API完全ガイド】

WindowsPowerShell
記事内に広告が含まれています。

PowerShellでのネットワーク操作を解説します。Test-Connection・Invoke-WebRequest・REST API呼び出しなど、ネットワーク関連の自動化に使えるコマンドレットをまとめます。

Test-Connection(pingの代わり)

Test-Connection -ComputerName "8.8.8.8" -Count 3

if (Test-Connection "hobbyshift.com" -Count 1 -Quiet) {
    Write-Host "接続OK"
} else {
    Write-Host "接続不可"
}

$hosts = @("8.8.8.8","1.1.1.1","hobbyshift.com")
$hosts | ForEach-Object {
    $ok = Test-Connection $_ -Count 1 -Quiet
    Write-Host "$_: OK=$ok"
}

Invoke-WebRequest

$res = Invoke-WebRequest "https://hobbyshift.com"
$res.StatusCode

Invoke-WebRequest "https://example.com/file.zip" -OutFile "C:\Downloads\file.zip"

$body = @{ Name="Taro"; Age=25 } | ConvertTo-Json
$res = Invoke-WebRequest "https://api.example.com/users" -Method POST -ContentType "application/json" -Body $body

Invoke-RestMethod(REST API)

$user = Invoke-RestMethod "https://api.github.com/users/microsoft"
Write-Host "フォロワー: $($user.followers)"

$headers = @{ Authorization = "Bearer $token" }
$data = Invoke-RestMethod "https://api.example.com/data" -Headers $headers

$body = @{ title="テスト"; body="内容" } | ConvertTo-Json
Invoke-RestMethod "https://jsonplaceholder.typicode.com/posts" -Method POST -ContentType "application/json" -Body $body

ネットワーク設定の確認

Get-NetIPAddress | Where-Object { $_.AddressFamily -eq "IPv4" }
Get-NetRoute -DestinationPrefix "0.0.0.0/0"
Get-DnsClientServerAddress
Get-NetTCPConnection -State Listen | Select-Object LocalPort,State | Sort-Object LocalPort

まとめ

  • Test-Connectionで疎通確認、-QuietオプションでTrue/Falseを返せる
  • Invoke-WebRequestでHTTPリクエストを送れる
  • Invoke-RestMethodはJSONを自動でオブジェクトに変換してREST APIと連携できる
  • Get-NetIPAddress・Get-NetRouteでネットワーク設定を確認できる

コメント

タイトルとURLをコピーしました