PowerCLI

  • 1.  VM MAC address to custom attribute

    Posted Jan 29, 2023 05:05 PM

    OK i tried and just can't seem to get it correct.  I tried reverse engineering a script from  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



  • 2.  RE: VM MAC address to custom attribute
    Best Answer

    Posted Jan 29, 2023 06:53 PM

    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
        }
    }

     



  • 3.  RE: VM MAC address to custom attribute

    Posted Jan 29, 2023 07:11 PM

    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.