本文介绍了Powershell将字符串转换为System.Net.IPAddress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是PowerShell的新手,我正在尝试自动创建DHCP保留.
I'm new to powershell and I'm trying to automate creating a DHCP reservation.
到目前为止,我已经可以像这样获得IP地址:
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
但是,Add-DhcpServer4Resrvation cmdlet不接受IP地址作为字符串.它要求IP地址为"System.Net.IpAddress"
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
如何将字符串转换为System.Net.IPAddress?
How do you convert a string to a System,.Net.IPAddress?
根据到此链接,它应该很容易
> [ipaddress]"192.0.2.1"
但是那行不通.
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
推荐答案
[IPAddress]
如果字符串中有空格,则无法正常工作
[IPAddress]
Wont work if there are spaces in the string
使用Trim()删除它们
Remove them with Trim()
$IP = [IPAddress]$IP.Trim()
这篇关于Powershell将字符串转换为System.Net.IPAddress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!