spuder
spuder

Reputation: 18387

Powershell convert String to System.Net.IPAddress

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

Upvotes: 5

Views: 25604

Answers (2)

Tech Stawk
Tech Stawk

Reputation: 11

A completely different approach for obtaining IP Address of a server is:

by passing the Workstation/Server name as a parameter to the input type System.Net.DNS cast

For example, if the FQDN name of the host is ABCTest-DEV, then the following script will reveal the IP address of ABCTest-Dev provided, the host has a DNS record already available in the domain.

$ipaddr = [System.Net.Dns]::GetHostAddresses('ABCTest-Dev')|Where AddressFamily -EQ 'InterNetwork'
Write-Host 'This IPV4 Address of the Host is: '$ipaddr

Upvotes: 1

spuder
spuder

Reputation: 18387

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

Remove them with Trim()

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

Upvotes: 11

Related Questions