2016-06-28 101 views
0

我创建了一个虚拟机,我想将其属性导出为CSV文件。
我所尝试的不会给我IPAddress,SwitchName,Macaddress。Powershell:获取虚拟机属性

$Data = @(); 
$VMs = Get-VM $VMName; 
foreach($VM in $VMs){ 
$VMCustom = New-Object System.Object; 
$VMCustom | Add-Member -Type NoteProperty -Name VMName -Value $VM.VMName; 
# Get-VMNetworkAdapter -VMName $VMName | Select -expand IPAddresses 
$VMCustom | Add-Member -Type NoteProperty -Name IPAddress -Value $VM.guest.IPAddresses; 
$VMCustom | Add-Member -Type NoteProperty -Name SwitchName -Value $VM.MacAddress; 
$VMCustom | Add-Member -Type NoteProperty -Name Status -Value $VM.State; 
$VMCustom | Add-Member -Type NoteProperty -Name Generation -Value $VM.Generation; 
$VMCustom | Add-Member -Type NoteProperty -Name SwitchName -Value $VM.SwitchName; 

$Data += $VMCustom; 
} 

$Data | Export-CSV "C:\VM.csv" -Delimiter ";"; 

问题:Ipaddress,VM的IP地址或Hyper-V的IP地址?

如果有人能帮助我,那将会很棒。

+0

在VMware,ip地址是IPv4和IPv6的地址阵列 - 因此,如果这是Hyper-V的情况下,尝试'$ vm.Guest.IPAddress [0]' – Avshalom

+0

错误:不可能在NULL数组上添加索引! – frhling1

+0

执行$ VM.IPAddresses并显示结果 – Avshalom

回答

0

试试这个:

$Data = @() 

$VMs = "Server-001","Server-002","Server-003" 

foreach($VM in $VMs) 
{ 
    $VMInfo = Get-VM -Name $VM 
    $VMNetwork = $VMInfo | Get-VMNetworkAdapter 

    $VMCustom = New-Object System.Object 
    $VMCustom | Add-Member -Type NoteProperty -Name VMName -Value $VMInfo.VMName 
    $VMCustom | Add-Member -Type NoteProperty -Name Status -Value $VMInfo.Status 
    $VMCustom | Add-Member -Type NoteProperty -Name Generation -Value $VMInfo.Generation 

    $VMCustom | Add-Member -Type NoteProperty -Name IPAddress -Value $VMNetwork.IPAddresses[0] 
    $VMCustom | Add-Member -Type NoteProperty -Name MacAddress -Value $VMNetwork.MacAddress 
    $VMCustom | Add-Member -Type NoteProperty -Name SwitchName -Value $VMNetwork.SwitchName 

    $Data += $VMCustom 
} 

$Data | Export-CSV "C:\VM.csv" -Delimiter ";" -NoTypeInformation 
+0

谢谢。除IPaddress之外的所有内容都是空的。如果IP是静态的或动态的,它有任何关系吗?是否可以添加一列来检查IP是静态的还是动态的? – frhling1

+0

如果你运行这个,它会返回什么?$ VMInfo = Get-VM -Name“Server-001”; $ VMNetwork = $ VMInfo | Get-VMNetworkAdapter; $ VMNetwork.IPAddresses – Oggew

+0

这很有趣。从昨天到今天,我什么也没有改变,但是今天它显示了IP地址。大。谢谢。 – frhling1