2015-04-30 22 views
1

的ip4v地址我是新來的PowerShell和我「米試圖得到的只是一個虛擬機的IPv4地址,並將其保存爲一個字符串PowerShell中,得到VM

我可以得到所有網絡屬性,像這樣:

PS C:\Windows\system32> get-vm | select -ExpandProperty networkadapters | select vmname, macaddress, switchname, ipaddres 
sses 

VMName      MacAddress     SwitchName     IPAddresses 
------      ----------     ----------     ----------- 
foobar          vSwitch      {192.0.2.1, fe80::84a... 

我可以同時獲得V4和V6發動機的IP地址

PS C:\Windows\system32> $IP = (GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses 
PS C:\Windows\system32> $IP 
192.0.2.1 
fe80::d47e: 
    ----------  

我怎樣才能得到公正的V4地址爲一個字符串?

更新

它看起來像有沒有對象的屬性,只是包括V4地址

PS C:\Windows\system32> GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter | Format-List -Property * 


IovWeight    : 0 
IovQueuePairsRequested : 1 
IovQueuePairsAssigned : 0 
IovInterruptModeration : Default 
IovUsage     : 0 
ClusterMonitored   : True 
VirtualFunction   : 
IsLegacy     : False 
IsManagementOs   : False 
IsExternalAdapter  : False 
Id      : Microsoft:xxxxxxxxxxx 
AdapterId    : xxxxxxxxxxx 
DynamicMacAddressEnabled : True 
MacAddress    : 00155D5B9B14 
MacAddressSpoofing  : Off 
SwitchId     : xxxxxxxxxxx 
Connected    : True 
PoolName     : 
SwitchName    : vSwitch 
AclList     : {} 
ExtendedAclList   : {} 
IsolationSetting   : Microsoft.HyperV.PowerShell.VMNetworkAdapterIsolationSetting 
CurrentIsolationMode  : Vlan 
RoutingDomainList  : {} 
DhcpGuard    : Off 
RouterGuard    : Off 
PortMirroringMode  : None 
IeeePriorityTag   : Off 
VirtualSubnetId   : 0 
DynamicIPAddressLimit : 0 
StormLimit    : 0 
AllowTeaming    : Off 
VMQWeight    : 100 
IPsecOffloadMaxSA  : 512 
VmqUsage     : 0 
IPsecOffloadSAUsage  : 0 
VFDataPathActive   : False 
VMQueue     : 
MandatoryFeatureId  : {} 
MandatoryFeatureName  : {} 
VlanSetting    : Microsoft.HyperV.PowerShell.VMNetworkAdapterVlanSetting 
BandwidthSetting   : 
BandwidthPercentage  : 0 
TestReplicaPoolName  : 
TestReplicaSwitchName : 
StatusDescription  : {OK} 
Status     : {Ok} 
IPAddresses    : {192.0.2.1, fe80::xxxxxxxxxxx} 
ComputerName    : xxxxxxxxxxx 
Name      : Network Adapter 
IsDeleted    : False 
VMId      : xxxxxxxxxxx 
VMName     : foobar 
VMSnapshotId    : 00000000-0000-0000-0000-000000000000 
VMSnapshotName   : 
Key      :                             

回答

3

你可以只篩選出具有任何IP「:」在裏面,因爲這樣:

$IP | ?{$_ -notmatch ':'} 
1

IPAddresses看起來像一個數組或服務,您只想要第一個於是嘗試:

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

不錯,雖然該列表是基於0的。應該是IpAddresses [0] – spuder

+0

並非每個設備都將具有IPv4地址。 –

+0

@ Erti-ChrisEelmaa只會舉例,不熟悉'Get-VM' cmdlet。你是對的,取決於其他反應可能會回來的。如果第一個項目總是你想要的那個,直接引用它是一種方式 –

1

假設只有1 V4地址,該地址V4是第一輸出,這樣做:

$IP = (GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses | Select-String -List 1