LoginSignup
1
4

More than 3 years have passed since last update.

【PowerShell】 IPアドレスの自動取得/手動設定の切り替え

Last updated at Posted at 2019-02-02

最近、PCをある機器に接続して使用する際、IPアドレスを自動取得/手動設定を切り替える必要がある。その際、ネットワークの設定~をいちいち開いて手動でアドレスを入力するのはとても面倒なため、自動化を試みた。バッチを使おうとも思ったが、折角powershellというものがあるため、使ってみた。

実行時にダイアログを出して自動取得/手動設定のどちらかを選択する、みたいなものはいちいち入力するのが面倒であるため、実行する度に自動取得/手動設定を切り替えるものとした。


# 管理者権限で実行できるようにする
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments # 別プロセスにて本処理を実行
    Break
}

# IPv4アドレス取得
$addr = [system.net.dns]::GetHostAddresses((hostname)) | where {$_.AddressFamily -eq "InterNetwork"} | select -ExpandProperty IPAddressToString

# 現在、IPアドレスが自動取得の場合は任意の値に、任意の値になっている場合は自動取得に設定する
if ($addr -eq "〇〇.〇〇.〇〇.〇〇") # IPアドレスが手動設定になっている場合(〇〇.〇〇.〇〇.〇〇にはアドレスを入力)
{
    netsh interface ipv4 set address name = "イーサネット" dhcp
    netsh interface ipv4 set dnsservers name = "イーサネット" dhcp
    echo "IPアドレスをDHCPからの自動取得に設定を変更しました。`n"
}
else # IPアドレスをDHCPサーバから自動取得している場合
{
    netsh interface ipv4 set add name = "イーサネット" source = static addr = "〇〇.〇〇.〇〇.〇〇" # 〇〇.〇〇.〇〇.〇〇にはアドレスを入力
    echo "IPアドレスを任意の値に変更しました。`n"
}

pause

ここがおかしい、ここ間違ってるぞ、ここはこうした方がいいぞ!等あれば、是非ご指摘いただけますと非常に喜びます。

1
4
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
1
4