簡體   English   中英

Powershell將ipv4地址放入變量中

[英]Powershell get ipv4 address into a variable

powershell 3.0 Windows 7中是否有一種簡單的方法可以將本地計算機的ipv4地址轉換為變量?

這是另一個解決方案:

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

這個怎么樣? (不是我的真實 IP 地址!)

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

PS C:\> $ipV4

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

請注意,使用 localhost 只會返回 127.0.0.1 的 IP

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

PS C:\> $ipV4

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

必須展開 IP 地址對象以獲取地址字符串

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

如果我使用機器名稱,這可以工作。 但是有點像 hack(因為我只是選擇了我得到的 ipv4 地址的第一個值。)

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

請注意,您必須替換上面表達式中的值PasteMachineNameHere

這也有效

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

以下是使用windows powershell和/或powershell core的三種方法,從最快到最慢列出。 您可以將其分配給您選擇的變量。



方法一:(這個方法最快,windows powershell和powershell core都可以)
 $ipAddress = (Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred" -and $_.ValidLifetime -lt "24:00:00"}).IPAddress


方法2:(此方法與方法1一樣快,但不適用於powershell內核)
$ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress


方法3:(雖然最慢,但是windows powershell和powershell core都可以)
 $ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress

(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress

這是我最終使用的

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

分解為

  • 執行 ipconfig 命令 - 獲取所有網絡接口信息
  • 使用帶有正則表達式的 powershell 過濾器
  • 正則表達式找到帶有“IPv4”的行和一組 4 個塊,每個塊有 1-3 個數字,用句點分隔,即 v4 IP 地址
  • 通過將其管道傳輸到 null 來忽略輸出
  • 最終得到正則表達式中括號定義的第一個匹配組。
  • 在 $ipaddress 中捕獲該輸出以供以后使用。

這一個班輪為您提供 IP 地址:

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

將其包含在變量中?

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

另一個使用$env環境變量來獲取主機名的變體:

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

或者如果您只想返回不帶屬性標頭的 IP 地址

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

tldr;

我使用此命令將我的以太網網絡適配器的 IP 地址放入一個名為 IP 的變量中。

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

對於那些想知道這一切意味着什么的人,請繼續閱讀

例如,大多數使用ipconfig的命令只是打印出你所有的 IP 地址,而我需要一個特定的 IP 地址,在我的情況下是用於我的以太網網絡適配器的。

您可以使用netsh interface ipv4 show interfaces命令查看網絡適配器列表。 大多數人需要 Wi-Fi 或以太網。

您將在命令提示符的輸出中看到這樣的表:

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)

在名稱欄中,您應該找到您想要的網絡適配器(即以太網、Wi-Fi 等)。

如前所述,就我而言,我對Ethernet很感興趣。

要獲取該適配器的 IP,我們可以使用 netsh 命令:

netsh interface ip show config name="Ethernet"

這給了我們這個輸出:

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

(出於安全原因,我偽造了上面的實際 IP 號碼😉)

我可以在 ms-dos 命令提示符中使用findstr命令進一步指定我想要的行。 在這里,我想要包含字符串IP Address的行。

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

這給出了以下輸出:

 IP Address:                           169.252.27.59

然后我可以使用for命令來解析文件(或在這種情況下為多行字符串)並根據分隔符和我感興趣的項目編號拆分字符串的內容。

請注意,我正在尋找第三項(tokens=3)並且我使用空格字符和:作為我的分隔符( delims=: )。

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

循環中的每個值或標記都被打印為變量 %i 但我只對第三個“標記”或項目感興趣(因此tokens=3 )。 請注意,我必須逃避| =使用^

for命令的末尾,您可以指定一個命令以使用返回的內容運行。 在這種情況下,我使用set將值分配給名為IP的環境變量。 如果您願意,您也可以只回顯該值或您喜歡的任何內容。

這樣,您將獲得一個環境變量,其中將首選網絡適配器的 IP 地址分配給環境變量。 很整潔吧?

如果您有任何改進的想法,請發表評論。

我一直在尋找同樣的東西並想通了這一點:

$ip = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile | Select-Object -ExpandProperty InterfaceIndex) | Select-Object -ExpandProperty IPAddress

這會過濾掉環回地址和我擁有的一些虛擬網絡。

獲取設備的 IPv4 地址,並過濾以僅獲取與您的方案匹配的地址(即忽略和 APIPA 地址或 LocalHost 地址)。 例如,您可以說抓取匹配192.168.200.*的地址。

$IPv4Addr = Get-NetIPAddress -AddressFamily ipV4 | where {$_.IPAddress -like X.X.X.X} | Select IPAddress
# Patrick Burwell's Ping Script - Patrick.Burwell@Infosys.com #
$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

當我在 Powershell 3 中工作時,這里沒有一個答案對我有用。 它基於 Rob 的方法,但是當您有多個網絡適配器時,此方法有效,它還使用捕獲組正確選擇 IP

function GetIPConfig {      
    return ipconfig | select-string  ('(\s)+IPv4.+\s(?<IP>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))(\s)*') -AllMatches | %{ $_.Matches } | % { $_.Groups["IP"]} | %{ $_.Value }
}
$ip = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile).InterfaceIndex).IPAddress

或者

function Get-LocalIP {
    (
        Get-NetIPAddress `
            -AddressFamily IPv4 `
            -InterfaceIndex $(
                Get-NetConnectionProfile
            ).InterfaceIndex
    ).IPAddress
}

$ip = Get-LocalIP

由於計算機可以有多個接口,而一個接口可以有多個 IP 地址,因此沒有一個最重要的評論實際上是完全正確的。 這里有一些答案在技術上是正確的,但使用“時髦”的方法來過濾掉眾所周知的地址(如 APIPA、localhost 等),而即使 Powershell 3.0 也有使用 PrefixOrigin 的本地方法。

$IPv4Addresses = $(Get-NetIPAddress | Where-Object { $_.PrefixOrigin -ne "WellKnown" -and $_.AddressFamily -eq "IPv4" }).IPAddress

我這樣做:

$interFaceAliasName="LAN" # You have to change the name according to your interface's name
$myInterface=(Get-NetIPAddress -InterfaceAlias $interFaceAliasName)
$myIP=$myInterface.IPv4Address

我最近有同樣的問題。 所以我寫了一個腳本來從ipconfig /all輸出中解析它。 這個腳本很容易修改以獲得接口的任何參數,它也適用於 Windows 7。

  1. LineNumber | Line LineNumber | Line格式

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

  1. LineNumber | Line中獲取接口列表(+ ipconfig輸出的最后一行) LineNumber | Line格式

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

  1. 篩選所需特定接口的接口列表

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

  1. 從輸出中獲取所選接口的開始和結束行號

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

  1. 從開始選擇線start..end

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

  1. 獲取 IP(v4) 地址字段(如果不存在 IPv4 地址,則返回 null)

$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. . . . . . . . . . . :",""

還要檢查 ipconfig 的哪個索引具有 IPv4 地址

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM