end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

VBScriptによるwin7のIP設定 (UAC対策として管理者として実行)

数日、「ヴァルヘルIPコンフィグ」という切替ツールを使ってみましたが、なんとなく使いづらいので、書いてみました。

Option Explicit
Dim ip_type, nic_name, ip, subnet, gw, dns1, dns2
Dim obj_sh, wsh, ip_cfg, str_line, ip_colon

nic_Name = "ワイヤレス ネットワーク接続"
ip =     "192.168.???.???"
subnet = "255.255.???.???"
gw     = "192.168.???.???"
dns1   = "192.47.???.???"
dns2   = "192.47.???.???"

Set obj_sh = CreateObject("Shell.Application")

'管理ユーザとして実行する為、再起動
If WScript.Arguments.length = 0 Then
    obj_sh.ShellExecute "wscript.exe", WScript.ScriptFullName+" uac","","runas"
    WScript.Quit
End If

ip_type = InputBox("DHCP(=d)? or STATIC IP(=s)?")

Set wsh = WScript.CreateObject("WScript.Shell")

'無指定の場合、static<->dhcpとします
If ip_Type = "" Then
    Set ip_cfg = wsh.Exec("ipconfig.exe")
    Do Until ip_cfg.StdOut.AtEndOfStream
        str_line = ip_cfg.StdOut.ReadLine
        If InStr(str_line, "IP Address") <> 0 Or _
           InStr(str_line, "IPv4 アドレス") <> 0 Then
            ip_colon = Instr(str_line, ":")
            str_line = Mid(str_line, ip_colon + 2)
            str_line = Replace(str_line, vbCr, "")
            If str_line = ip Then
                ip_Type = "d"
            Else
                ip_Type = "s"
            End if
        End If
    Loop
End If

If ip_Type = "d" Then
    wsh.Run "cmd.exe /c netsh interface ip set address """ & _
        nic_Name &""" dhcp"
    wsh.Run "cmd.exe /c netsh interface ip set dns """ & _
        nic_Name &""" dhcp"
    MsgBox "IPアドレスDHCP設定完了"
    WScript.Quit
End If

If ip_Type = "s" Then
    wsh.Run "cmd.exe /c netsh interface ip set address """ & nic_name & _
             """ static " & ip & " " & subnet & " " & gw, 0, True
    wsh.Run "cmd.exe /c netsh interface ip set dns """ & nic_Name & _
            """ static " & dns1, 0, True
    wsh.Run "cmd.exe /c netsh interface ip add dns """ & nic_Name & _
            """ addr=" & dns2 ,0, True
    MsgBox "IPアドレス設定完了"
    WScript.Quit
End If

wscript.exeは runasを指定すると、管理者として実行するらしい。
管理者として実行すれば、後はnetshで設定するだけです。