Powershell get ipv4 address into a variable

后端 未结 12 2327
长情又很酷
长情又很酷 2021-01-31 08:23

Is there an easy way in powershell 3.0 Windows 7 to get the local computer\'s ipv4 address into a variable?

12条回答
  •  难免孤独
    2021-01-31 09:21

    Here are three methods using windows powershell and/or powershell core, listed from fastest to slowest. You can assign it to a variable of your choosing.



    Method 1: (this method is the fastest and works in both windows powershell and powershell core)
    $ipAddress = (Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred" -and $_.ValidLifetime -lt "24:00:00"}).IPAddress
    


    Method 2: (this method is as fast as method 1 but it does not work with powershell core)
    $ipAddress = (Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPv4Address).IPAddressToString
    


    Method 3: (although the slowest, it works on both windows powershell and powershell core)
    $ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress
    

提交回复
热议问题