我正在使用RenewDHCPLease()更新系统的IP地址。

  • RenewDHCPLease()ipconfig /renew之间的确切区别是什么?
  • 在Powershell中使用哪个更好?
  • 是否有必要在ReleaseDHCPLease()之前使用RenewDHCPLease()?如果可以,为什么?

  • 下面是我的代码:
    try {
        $ips = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where { $_.IpEnabled -eq $true -and $_.DhcpEnabled -eq $true} -ErrorAction Stop
        if (!$ips) {
            Write-Output "`nDHCP is not Enabled on this system"
            Exit
        }
        foreach ($ip in $ips) {
            Write-Output "`nRenewing IP Addresses"
            $ip.RenewDHCPLease() | Out-Null
            if ($?) {
                Write-Output "IP address has been renewed for this system"
            }
            else {
                Write-Error "IP Address Could not be renewed"
            }
        }
    }
    catch {
        $_.Exception.Message
    }
    

    最佳答案

    ReleaseDHCPLease releases the IP address bound to a specific DHCP enabled network adapterRenewDHCPLease Renews the IP address on a specific DHCP enabled network adapter

    由于使用ReleaseDHCPLease时会释放旧地址并自动获取新地址,因此无需在RenewDHCPLease之前使用RenewDHCPLease

    Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IpEnabled=True AND DhcpEnabled=True' | Foreach-Object{
        $_.RenewDHCPLease()
    }
    

    您也可以使用RenewDHCPLeaseAll方法立即更新它们。希望这可以帮助 :)

    08-06 20:23