Question:
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:
1 2 |
$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses[0] |
This returns a string like:
1 2 |
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’
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 2 |
> [ipaddress]"192.0.2.1" |
However that doesn’t work.
1 2 3 4 5 6 7 8 9 10 11 12 |
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
Answer:
[IPAddress]
Wont work if there are spaces in the string
Remove them with Trim()
1 2 |
$IP = [IPAddress]$IP.Trim() |