【发布时间】:2014-12-03 17:14:38
【问题描述】:
powershell 3.0 Windows 7中是否有简单的方法将本地计算机的ipv4地址获取到变量中?
【问题讨论】:
powershell 3.0 Windows 7中是否有简单的方法将本地计算机的ipv4地址获取到变量中?
【问题讨论】:
这是另一个解决方案:
$env:HostIP = (
Get-NetIPConfiguration |
Where-Object {
$_.IPv4DefaultGateway -ne $null -and
$_.NetAdapter.Status -ne "Disconnected"
}
).IPv4Address.IPAddress
【讨论】:
$i=Get-NetIPConfiguration|Where-Object{$_.ipv4defaultgateway -ne $null};$i.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
【讨论】:
$ip = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString
(hostname) 调用外部实用程序,方法是使用$env:COMPUTERNAME 环境变量,即Test-Connection $env:COMPUTERNAME -Count 1 | Select IPV4Address。
$ipv4 = (Test-Connection -ComputerName $env:ComputerName -Count 1).IPV4Address.IPAddressToString 我在连接到有线网络的系统上对此进行了测试,结果显示 IPv4。未连接到任何网络时显示家庭 (127.0.0.1),连接到无线时显示 IPv4。
如果我使用机器名称,则可以。但是有点像 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]
【讨论】:
Program 'ipconfig.exe' failed to run: The directory name is invalidAt line:1 char:20 $localIpAddress=(( ipconfig | findstr [0-9].\.)[0]).Split()[-1] + ~~~~~~~~. At line:1 char:1 + $localIpAddress=(( ipconfig | findstr [0-9].\.)[0]).Split()[-1] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed
以下是使用 windows powershell 和/或 powershell core 的三种方法,从最快到最慢列出。 您可以将其分配给您选择的变量。
【讨论】:
(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress
【讨论】:
DHCPEnabled=True。此命令的输出与@Lucas (Get-NetIPConfiguration) 提供的不同。
这是我最终使用的
$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])
分解为
【讨论】:
这一行给你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
【讨论】:
我使用此命令将以太网网络适配器的 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 地址,而我需要一个特定的地址,在我的情况下是用于我的以太网网络适配器。
您可以使用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
【讨论】:
没有一个顶级 cmets 实际上是完全正确的,因为一台计算机可以有多个接口,而一个接口可以有多个 IP 地址。这里有一些答案在技术上是正确的,但使用“时髦”的方式来过滤掉众所周知的地址(如 APIPA、localhost 等),而即使 Powershell 3.0 也有使用 PrefixOrigin 的原生方式。
$IPv4Addresses = $(Get-NetIPAddress | Where-Object { $_.PrefixOrigin -ne "WellKnown" -and $_.AddressFamily -eq "IPv4" }).IPAddress
【讨论】:
我最近遇到了同样的问题。所以我写了一个脚本来从ipconfig /all 输出中解析它。这个脚本很容易修改以获得接口的任何参数,它也可以在 Windows 7 上运行。
LineNumber | Line 格式获取 IP 配置的输出$ip_config = $(ipconfig /all | % {$_ -split "rn"} | Select-String -Pattern ".*" | select LineNumber, Line)
LineNumber | Line 格式获取接口列表(+ipconfig 输出的最后一行)$interfaces = $($ip_config | where {$_.Line -notmatch '^\s*$'} | where {$_.Line -notmatch '^\s'}) + $($ip_config | Select -last 1)
$LAN = $($interfaces | where {$_.Line -match 'Wireless Network Connection:$'})
$i = $interfaces.IndexOf($LAN)$start = $LAN.LineNumber$end = $interfaces[$i+1].LineNumber
start..end中选择行
$LAN = $ip_config | where {$_.LineNumber -in ($start..$end)}
$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 地址
【讨论】: