[windows] Powershell get ipv4 address into a variable

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

This question is related to windows powershell-3.0

The answer is


This one liner gives you the IP address:

(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString

Include it in a Variable?

$IPV4=(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString

How about this? (not my real IP Address!)

PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select IPV4Address

PS C:\> $ipV4

IPV4Address                                                  
-----------
192.0.2.0

Note that using localhost would just return and IP of 127.0.0.1

PS C:\> $ipV4 = Test-Connection -ComputerName localhost -Count 1  | Select IPV4Address

PS C:\> $ipV4

IPV4Address                                                             
-----------                                                  
127.0.0.1

The IP Address object has to be expanded out to get the address string

PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select -ExpandProperty IPV4Address 

PS C:\> $ipV4

Address            : 556228818
AddressFamily      : InterNetwork
ScopeId            : 
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 192.0.2.0


PS C:\> $ipV4.IPAddressToString
192.0.2.0

Here is what I ended up using

$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])

which breaks down as

  • execute ipconfig command - get all the network interface information
  • use powershell's where filter with a regular expression
  • regular expression finds the line with "IPv4" and a set of 4 blocks each with 1-3 digits separated by periods, i.e. a v4 IP address
  • disregard the output by piping it to null
  • finally get the first matched group as defined by the brackets in the regular expression.
  • catch that output in $ipaddress for later use.

(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DefaultIPGateway -ne $null}).IPAddress | select-object -first 1

Here is another solution:

$env:HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress

tldr;

I used this command to get the ip address of my Ethernet network adapter into a variable called IP.

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

For those who are curious to know what all that means, read on

Most commands using ipconfig for example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.

You can see your list of network adapters by using the netsh interface ipv4 show interfaces command. Most people need Wi-Fi or Ethernet.

You'll see a table like so in the output to the command prompt:

Idx     Met         MTU          State                Name
---  ----------  ----------  ------------  ---------------------------
  1          75  4294967295  connected     Loopback Pseudo-Interface 1
 15          25        1500  connected     Ethernet
 17        5000        1500  connected     vEthernet (Default Switch)
 32          15        1500  connected     vEthernet (DockerNAT)

In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).

As mentioned, I was interested in Ethernet in my case.

To get the IP for that adapter we can use the netsh command:

netsh interface ip show config name="Ethernet"

This gives us this output:

Configuration for interface "Ethernet"
    DHCP enabled:                         Yes
    IP Address:                           169.252.27.59
    Subnet Prefix:                        169.252.0.0/16 (mask 255.255.0.0)
    InterfaceMetric:                      25
    DNS servers configured through DHCP:  None
    Register with which suffix:           Primary only
    WINS servers configured through DHCP: None

(I faked the actual IP number above for security reasons )

I can further specify which line I want using the findstr command in the ms-dos command prompt. Here I want the line containing the string IP Address.

netsh interface ip show config name="Ethernet" | findstr "IP Address"

This gives the following output:

 IP Address:                           169.252.27.59

I can then use the for command that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.

Note that I am looking for the third item (tokens=3) and that I am using the space character and : as my delimiters (delims=: ).

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3). Note that I had to escape the | and = using a ^

At the end of the for command you can specify a command to run with the content that is returned. In this case I am using set to assign the value to an environment variable called IP. If you want you could also just echo the value or what ever you like.

With that you get an environment variable with the IP Address of your preferred network adapter assigned to an environment variable. Pretty neat, huh?

If you have any ideas for improving please leave a comment.


If I use the machine name this works. But is kind of like a hack (because I am just picking the first value of ipv4 address that I get.)

$ipaddress=([System.Net.DNS]::GetHostAddresses('PasteMachineNameHere')|Where-Object {$_.AddressFamily -eq "InterNetwork"}   |  select-object IPAddressToString)[0].IPAddressToString

Note that you have to replace the value PasteMachineNameHere in the above expression

This works too

$localIpAddress=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]

I recently had the same issue. So I wrote a script to parse it from the ipconfig /all output. This script is easily modifiable to obtain any of the parameters of the interfaces and it works on Windows 7 also.

  1. Get output of IP config in LineNumber | Line format

$ip_config = $(ipconfig /all | % {$_ -split "rn"} | Select-String -Pattern ".*" | select LineNumber, Line)

  1. Get list of interfaces (+ last line of ipconfig output) in LineNumber | Line format

$interfaces = $($ip_config | where {$_.Line -notmatch '^\s*$'} | where {$_.Line -notmatch '^\s'}) + $($ip_config | Select -last 1)

  1. Filter through the interfaces list for the specific interface you want

$LAN = $($interfaces | where {$_.Line -match 'Wireless Network Connection:$'})

  1. Get the start and end line numbers of chosen interface from output

$i = $interfaces.IndexOf($LAN)
$start = $LAN.LineNumber
$end = $interfaces[$i+1].LineNumber

  1. Pick the lines from start..end

$LAN = $ip_config | where {$_.LineNumber -in ($start..$end)}

  1. Get IP(v4) address field (returns null if no IPv4 address present)

$LAN_IP = @($LAN | where {$_ -match 'IPv4.+:\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'})
$LAN_IP = &{If ($LAN_IP.Count -gt 0) {$Matches[1]} Else {$null}}


$a = ipconfig
$result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""

Also check which index of ipconfig has the IPv4 Address


# Patrick Burwell's Ping Script - [email protected] #
$Output= @() #sets an array
$names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against 
  if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
  ){# If true then run...
   $Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
   Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
  }
  else{#If false then run...
    $Output+= "$name," #Fills the array with the #false response
    Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors 
  }
}

#$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
#$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)

#If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments

Another variant using $env environment variable to grab hostname:

Test-Connection -ComputerName $env:computername -count 1 | Select-Object IPV4Address

or if you just want the IP address returned without the property header

(Test-Connection -ComputerName $env:computername -count 1).IPV4Address.ipaddressTOstring

To grab the device's IPv4 addresses, and filter to only grab ones that match your scheme (i.e. Ignore and APIPA addresses or the LocalHost address). You could say to grab the address matching 192.168.200.* for example.

$IPv4Addr = Get-NetIPAddress -AddressFamily ipV4 | where {$_.IPAddress -like X.X.X.X} | Select IPAddress

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