Search code examples
powershellwmidhcp

How to get dhcp lease expire time with WMI?


Now I'm using Get-DhcpServerv4Lease -ComputerName 'pc' -ScopeId 'id' -AllLeases with $object.leaseExpiryTime to get lease expiry time.

But is it possible to get it with WMI query? Kindly ask you for example.


Solution

  • Use Win32_NetworkAdapterConfiguration, as it does contain DHCPLeaseExpires. As for an example,

    gwmi -query "select DHCPLeaseExpires, ipaddress, Description from Win32_NetworkAdapterConfiguration where dhcpleaseexpires is not null"
    # Output
    Description      : Intel(R) Dual Band Wireless-AC 8265
    DHCPLeaseExpires : 20200604032809.000000+180
    IPAddress        : {192.168.1.104, fe80::...}
    

    To convert DHCPLeaseExpires into a .Net DateTime, use ManagementDateTimeConverter.ToDateTime(String) from System.Management. A DateTime supports several formatting strings like so,

    $wlan = gwmi -query "select ..."
    Add-Type -AssemblyName System.Management
    $t = [Management.ManagementDateTimeConverter]::ToDateTime($wlan.DHCPLeaseExpires)
    $t.GetType()                                                                            
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     DateTime                                 System.ValueType
    
    $t.ToString('u')
    2020-06-04 03:28:09Z
    
    $t.ToString('G')                                                                        
    4.6.2020 3:28:09