Powershell convert String to System.Net.IPAddress

China☆狼群 提交于 2020-01-15 07:19:32

问题


I'm new to powershell and I'm trying to automate creating a DHCP reservation.

So far I'm able to get the IP address like so:

$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses[0]

This returns a string like:

192.0.2.1

However, the Add-DhcpServer4Resrvation cmdlet does not accept an ip address as a string. It requires the IP address be a 'System.Net.IpAddress'

Add-DhcpServerv4Reservation -ComputerName $DHCPServer -ScopeId $DHCPScope -IPAddress $IP -Client
Id $MacAddress -Name $HVNAME

Add-DhcpServerv4Reservation : Cannot process argument transformation on parameter 'IPAddress'. Cannot convert value "
10.254.130.104
" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
At line:1 char:86
+ ... ope -IPAddress $IP -ClientId $MacAddress -Name $HVNAME
+                    ~~~
    + CategoryInfo          : InvalidData: (:) [Add-DhcpServerv4Reservation], ParameterBindingArgumentTransformationEx
   ception
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Add-DhcpServerv4Reservation

How do you convert a string to a System,.Net.IPAddress?

According to this link, it should be easy like

> [ipaddress]"192.0.2.1"

However that doesn't work.

PS C:\Windows\system32> $FOO = [IPAddress]$IP
Cannot convert value "
10.254.130.104
" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
At line:1 char:1
+ $FOO = [IPAddress]$IP
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocation
                   tworkAdapter) Format-List -Property *.254.13༁爼ሂÌGEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter) | Format-List -Property *    {༁牎ᐂÊGEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter | Format-List -Property *
ఁ牘ࠂÆ$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Gt-VMNex뿰bpte

Related question
Powershell, get ip4v address of VM


回答1:


[IPAddress] Wont work if there are spaces in the string

Remove them with Trim()

$IP = [IPAddress]$IP.Trim()


来源:https://stackoverflow.com/questions/29977500/powershell-convert-string-to-system-net-ipaddress

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!