2016-06-28 103 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