Report for all vms regarding uuid,network card, macaddress, ipaddress, network card type e1000/vmxnet in a csv ;)

Right,
i wanted to see all vms, with their current ips, macaddresses, names, networkcard types.
This report should also have all network cards in separate columns in csv. So i needed to dynamically adjust number of those ‘columns’.
Below script will output only ipv4 addresses without ipv6.

$reportedvms=New-Object System.Collections.ArrayList
$vms=get-view -viewtype virtualmachine  |Sort-Object -Property {  $_.Config.Hardware.Device |  where {$_ -is [VMware.Vim.VirtualEthernetCard]} |  Measure-Object | select -ExpandProperty Count} -Descending 

foreach($vm in $vms){
  $reportedvm = New-Object PSObject
  Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Guest -value $vm.Name
  Add-Member -InputObject $reportedvm -MemberType noteProperty -name UUID -value $($vm.Config.Uuid)
$networkcards=$vm.guest.net | ?{$_.DeviceConfigId -ne -1}
$i=0
foreach($ntwkcard in $networkcards){
Add-Member -InputObject $reportedvm -MemberType NoteProperty -Name "networkcard${i}.Network" -Value $ntwkcard.Network
Add-Member -InputObject $reportedvm -MemberType NoteProperty -Name "networkcard${i}.MacAddress" -Value $ntwkcard.Macaddress  
Add-Member -InputObject $reportedvm -MemberType NoteProperty -Name "networkcard${i}.IpAddress" -Value $($ntwkcard.IpAddress|?{$_ -like "*.*"})
Add-Member -InputObject $reportedvm -MemberType NoteProperty -Name "networkcard${i}.Device" -Value $(($vm.config.hardware.device|?{$_.key -eq $($ntwkcard.DeviceConfigId)}).gettype().name)
$i++
}
$reportedvms.add($reportedvm)|Out-Null
}

$reportedvms|Export-Csv c:\myreport.csv

Ok, and what if somebody doesn’t want those multiple columns, but wants to have only 1 column that will describe all network cards for particular vm ?

$vms=get-view -viewtype virtualmachine
$(
foreach($vm in $vms){
$networkcards=$vm.guest.net | ?{$_.DeviceConfigId -ne -1}
""|select  @{n="VM name";e={$vm.name}},@{n="uuid";e={$vm.config.uuid}},@{n="net  info";e={[string]::join(',',  $($networkcards|%{$devid=$_.DeviceConfigId;[string]::join(',',$(($vm.config.hardware.device|?{$_.key  -eq $devid}).gettype().name,$_.network,($_.ipaddress -join ';'),$_.Macaddress))})  )}}
}
)|export-csv c:\myreport.csv

I know 😉 a lot of joining.
@Update: Luc has noticed my error there that i was not sorting $vms array. We have to sort it by the vm with most network cards so that export-csv will work properly.
@Update: Thanks Steve for the feedback. I have updated the code in both examples.
27/02/2014@Update : Fixed issue with reporting multiple ip addresses in second example.

Advertisements

Searching for cdrom devices with Emulate Ide or Passthrough IDE mode in powercli

Right,
so we want to find all vms that have their cdrom device set to Emulate Ide mode.

$vms=get-view -viewtype virtualmachine
foreach($vm in $vms){
 if ($vm.Config.Hardware.Device |? {$_.backing -is [vmware.vim.VirtualCdromRemoteAtapiBackingInfo]}) {$vm.name}
}

If we want to look for vms with cdrom devices mode set to Passthrough:

$vms=get-view -viewtype virtualmachine
foreach($vm in $vms){
 if ($vm.Config.Hardware.Device |? {$_.backing -is [vmware.vim.VirtualCdromRemotePassthroughBackingInfo]}) {$vm.name}
}

No fancy output 😉 Just sending to screen affected vm names.

‘Cannot complete the HA configuration’ yellow popup message via powercli

I have noticed some day that issue like on screenshot below is not going to the Alert tab. 99% that some other alert created this message, for example host is loosing uplink will result in having this popup to show up. I was wondering how it is possible for me to monitor those yellow popups in summary tab 😉

The easiest way to get information about this popup is to check the configissue property of vmhost object.

$myhost=get-vmhost 'myhost'
$myhost.extensiondata.configissue
-
Message              :
Reason               : agentFailed
Key                  : 0
ChainId              : 0
CreatedTime          : 8/9/2012 12:27:41 PM
UserName             :
Datacenter           : VMware.Vim.DatacenterEventArgument
ComputeResource      : VMware.Vim.ComputeResourceEventArgument
Host                 : VMware.Vim.HostEventArgument
Vm                   :
Ds                   :
Net                  :
Dvs                  :
FullFormattedMessage : HA agent on myhost in cluster X in Y DC has an error :  HA agent on the host failed
ChangeTag            :
DynamicType          :
DynamicProperty      :

That’s pretty much it 😉 In this object there will be FullFormattedMessage property that will describe current issue. From here is now easy to write some little report that will inform us if we have any config issues on our hosts.

Find out if host has a portgroup with vlan X

Situation : Your portgroup names doesn’t make any sense, and it’s not easy to tell tell vlan id from the name. If you want quickly to discover if you have some portgroup on vswitch that handles vlan X this could be handy:

Get-VMHost your_host| Get-VirtualPortGroup | ? {$_.Vlanid -eq 777} | select name,vlanid

This will check if we have any portgroup defined for ‘your_host’ vswitch.

ESX/ESXi host in vCenter Server reports the error: Unable to apply DRS resource settings on host. The operation is not allowed in the current state

What helped in my situation:
service mgmt-vmware restart
on the service console
Official KB for this situation:
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1028351

Set-NetworkAdapter The operation for the entity VirtualMachine-vm- failed with the following message: “Invalid configuration for device ‘0’.”

When trying to set the connected property of a network card within virtual machine you receive:

Get-VM -name XYZ | Get-NetworkAdapter | Set-NetworkAdapter -Connected:$true 
Set-NetworkAdapter : 7/6/2012 10:59:14 AM    Set-NetworkAdapter        The operation for the entity VirtualMachine-vm-777 failed with the following message: "
Invalid configuration for device '0'."

If you use vCenter Server 5.0, vCenter Server 5.0 Update 1, ESXi 5.0, and ESXi 5.0 Update 1. then you could be probably affected by this problem described here
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2013639
What will happen :
You will notice that your vm nics are not “connected” although they have setting “connect at power on” checked.
If you will try to check the “connected” property you will receive error “Invalid configuration for device ‘0’
There is no way to fix this issue on a permanent basis. All you can do now is to proceed with vmware KB 2013639 in order to fix your vms. There is a powercli script attached in the KB, download it and execute it:

# Get-VM | Test-VDSVMIssue
This will show you which vm is affected
# Get-vm | Test-VDSVMIssue -fix  
This will try to fix issue for all your vms 

If you want to test it first for a particular vm select one using :

get-vm -name "your vm" | Test-VDSVMIssue -fix

What happens is that if your vm is affected by this issue, it looses information about its vmnic portid in the vmnic portgroup.
The script provided by vmware fixes this by changing the portid for this vmnic and then reverting the portid to the old portid.
You can check it manually if you are affected by doing following steps:
Open vSphere client , switch to networking view, and select the portgroup where your vm has vmnics attached.
Open your vm vmx file to check which portid was configured. You can read the vmx file using ssh to esxi host or download the vmx file using datastore browser within vSphere client.
When your vm vmnic is using distributed vswitch you will see entries like those:

ethernet0.dvs.switchId = "8d 7e 0b 50 67 e4 0b 46-3f 30 0b f8 d5 6a 58 f3"
ethernet0.dvs.portId = "1234"

In case you are affected, you will notice that although you can see that this vmnic is using this portid(verified by checking portgroup in vSphere client) there is no file on datastore
in vds directory ‘.dvsData/ethernet0.dvs.switchId’ where ethernet0.dvs.switchId should be changed to your switch id
That’s why we can not change the state of vmnic to connected.
Run the vmware powercli script from KB, it should tell you that problem was fixed.
If you will now check the .dvsData/switchID directory you should find a file with name of the portID that was choosen for this vmnic
From that moment go to vm and select “connected” property to on. You should not see the Invalid configuration for device ‘0’ error again.
You can experience this problem even if your vms are not using sdrs.
If you have large amount of vms that are affected by this and you want to automate process of selecting “connected”, you can automate checking the ‘connect’ box property using :

get-vm -Name AffectedVM | Get-NetworkAdapter  | select connectionstate 
#check if it is disconnected, after the applying the fix for this vm use
get-vm -Name AffectedVM | Get-NetworkAdapter  | Set-NetworkAdapter -Connected:$true -Confirm:$false
#this will enable the 'connected' property

if you have more than 1 vm for which you want to edit this property you can list them in this one command

get-vm -Name AffectedVM,AffectedVM2,AffectedVM3 | Get-NetworkAdapter  | Set-NetworkAdapter -Connected:$true -Confirm:$false 

new-drsrule Unable to cast object of type ‘VMware.Vim.ClusterVmHostRuleInfo’ to type ‘VMware.Vim.ClusterAntiAffinityRuleSpec’.

I was trying to create a new drs vm-vm anti affinity rule and got this red error :

PowerCLI C:\> New-DrsRule -Cluster xyz -Name AA-vm1,vm2 -KeepTogether:$false -VM vm1,vm2
2
New-DrsRule : 5/14/2012 9:30:23 AM New-DrsRule Unable to cast object of type 'VMware.Vim.ClusterVmHostRuleInf
o' to type 'VMware.Vim.ClusterAntiAffinityRuleSpec'.
At line:1 char:12
+ New-DrsRule <<<< -Cluster xyz -Name AA-vm1,vm2 -KeepTogether:$false -VM vm1,vm2
+ CategoryInfo : NotSpecified: (:) [New-DrsRule], ViError
+ FullyQualifiedErrorId : Client20_ClientSideTaskImpl_ThreadProc_UnhandledException,VMware.VimAutomation.ViCore.Cm
dlets.Commands.NewDrsRule

Still , i do not know if there is a way to fix this , or is this just a bug and will be fixed in new release of powercli.
This error is only “informing” us, and the rule is still created on this cluster, so i would say that this is only a minor issue. But if you are not happy that it outputs those nasty red errors, you can do other function that ads a vm-vm rule on a cluster , i will write function later, but if want to write it yourself this should be more than enough in order to write it:

$spec2 = New-Object VMware.Vim.ClusterConfigSpecEx
$spec2.rulesSpec = New-Object VMware.Vim.ClusterRuleSpec[] (2)
$spec2.rulesSpec[0] = New-Object VMware.Vim.ClusterRuleSpec
$spec2.rulesSpec[0].operation = "add"
$spec2.rulesSpec[0].info = New-Object VMware.Vim.ClusterAffinityRuleSpec            
$spec2.rulesSpec[0].info.enabled = $true
$spec2.rulesSpec[0].info.name = "AA-vm1-vm2"
$spec2.rulesSpec[0].info.userCreated = $true
$spec2.rulesSpec[0].info.vm = (get-vm vm1,vm2|get-view) |% {$_.moref}  
(Get-View -Id (get-cluster xyz).id).ReconfigureComputeResource_Task($spec2, $true)

# object for AA rule is VMware.Vim.ClusterAntiAffinityRuleSpec
# you can put as many vms as you want in info.vm section...

Today is diablo3 world premiere 😉 so um… i will not write this function today 😉
Why this error is showing up ? that’s because i have used a VM-TO-HOST rule on cluster. Once you define a rule like that, new-drsrule will output this error while creating a VM-VM rule on that cluster. I have observed this on powercli 5.0.1. Same for remove-drsRule, when you will specify a vm-host rule, it will also FAIL, not just by screaming with error, but the deleting will not proceed. I will also write a function for this , but like i said not today 😉
I will post a pack of drs functions shortly with add/remove and so on. This topic was mentioned on vmware communities, you can open it using this link and check how to reproduce this error step by step.
http://communities.vmware.com/thread/401845
UPDATE:
VMware has confirmed this bug, and wrote that it is fixed in new release. Nice!