VMware Cloud Community
willster07
Contributor
Contributor
Jump to solution

VM MAC address to custom attribute

OK i tried and just can't seem to get it correct.  I tried reverse engineering a script from @LucD to now add a custom attribute to vSphere, the MAC address of the device, it's not getting it populated.  The below does output the MAC addresses into the console.  It will also of course create the attribute MAC in vSphere.  But I'm also looking for only the first entry on any given VM if there are multiple NICs on the VM.

$caName = 'MAC'
 try {
 $ca = Get-CustomAttribute -Name $caName -ErrorAction Stop
 } catch {
 $ca = New-CustomAttribute -Name $caName -TargetType VirtualMachine
 }
 Get-VM -name "*" | Get-NetworkAdapter | select -ExpandProperty MacAddress
 Where-Object { $_.MacAddress } |
 ForEach-Object -Process {
 Set-Annotation -Entity $_ -CustomAttribute $ca -Value $_.MacAddress
 }

Get-Variable shows this:

Get-CustomAttribute CustomAttribute with name 'MAC' was not fo...

How does one go about finding the full error?  I'm assuming it say it was not found but I dont' know for sure.

 

Thanks a bunch.  Last one for vsphere attributes i promise 🙂

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Try something like this.
It uses the PipelineVariable parameter on the Get-VM cmdlet, so that we can use that to refer to the VM on the Set-Annotation cmdlet.

You can use $error[0] to see the last error message

$caName = 'MAC'
try {
    $ca = Get-CustomAttribute -Name $caName -ErrorAction Stop
} catch {
    $ca = New-CustomAttribute -Name $caName -TargetType VirtualMachine
}
Get-VM -PipelineVariable vm | 
ForEach-Object -Process {
  Get-NetworkAdapter -VM $vm | Where-Object { $_.MacAddress } |
    select -First 1 |
    ForEach-Object -Process {
        Set-Annotation -Entity $vm -CustomAttribute $ca -Value $_.MacAddress
    }
}

 


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

2 Replies
LucD
Leadership
Leadership
Jump to solution

Try something like this.
It uses the PipelineVariable parameter on the Get-VM cmdlet, so that we can use that to refer to the VM on the Set-Annotation cmdlet.

You can use $error[0] to see the last error message

$caName = 'MAC'
try {
    $ca = Get-CustomAttribute -Name $caName -ErrorAction Stop
} catch {
    $ca = New-CustomAttribute -Name $caName -TargetType VirtualMachine
}
Get-VM -PipelineVariable vm | 
ForEach-Object -Process {
  Get-NetworkAdapter -VM $vm | Where-Object { $_.MacAddress } |
    select -First 1 |
    ForEach-Object -Process {
        Set-Annotation -Entity $vm -CustomAttribute $ca -Value $_.MacAddress
    }
}

 


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

willster07
Contributor
Contributor
Jump to solution

You sir are a rock star!  Worked flawlessly!

Generally I wouldn't show something like this but it seems worth an exception, all your help paid off.

0 Kudos