我是PowerShell的新手,我尝试自动创建DHCP预留。
到目前为止,我能够像这样获得IP地址:
$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses[0]
返回如下字符串:
192.0.2.1
但是,Add-DhcpServer4Resrvation cmdlet不接受ip地址作为字符串。它要求IP地址为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?
根据to this link,它应该很容易
> [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
答案 0 :(得分:7)
[IPAddress]
如果字符串中有空格
使用Trim()
删除它们$IP = [IPAddress]$IP.Trim()
答案 1 :(得分:0)
获取服务器IP地址的完全不同的方法是:
通过将工作站/服务器名称作为参数传递给输入类型System.Net.DNS cast
例如,如果主机的FQDN名称为ABCTest-DEV,则以下脚本将显示提供的ABCTest-Dev的IP地址,该主机在域中已经有DNS记录。
$ipaddr = [System.Net.Dns]::GetHostAddresses('ABCTest-Dev')|Where AddressFamily -EQ 'InterNetwork'
Write-Host 'This IPV4 Address of the Host is: '$ipaddr