Powershell get ipv4 address into a variable

后端 未结 12 2321
长情又很酷
长情又很酷 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:16

    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

提交回复
热议问题