PowerCLI

 View Only
  • 1.  Get License information

    Posted Oct 30, 2024 08:37 AM

    Hi All,

    I need assistance obtaining information about temporary licenses.

    function Get-ESXiHostInventory {
        param (
            [Parameter(Mandatory = $true)]
            [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$vmHost
        )

        # Initialize hardware information variables and set default values
        $hardwareInfo = @{ }
        $serialNumber = "Not Retrieved"
        $licenseStatus = "Unknown"

        # Get basic hardware information via Get-View (vSphere API) for ESXi hosts
        try {
            $hostView = $vmHost | Get-View
            $totalCpuCores = $hostView.Hardware.CpuInfo.NumCpuCores

            $hardwareInfo = @{
                Hostname        = $vmHost.Name
                ConnectionState = $vmHost.ConnectionState
                PowerState      = $vmHost.PowerState
                CpuTotalGHz     = [math]::round(($hostView.Hardware.CpuInfo.Hz * $totalCpuCores) / 1e9, 2) # Hz to GHz
                CpuUsageGHz     = [math]::round($vmHost.CpuUsageMhz / 1000, 2) # MHz to GHz
                CpuCount        = $hostView.Hardware.CpuInfo.NumCpuPackages
                TotalCPUCores   = $totalCpuCores
                MemoryTotalGB   = [math]::round($vmHost.MemoryTotalGB, 2)
                MemoryUsageGB   = [math]::round($vmHost.MemoryUsageGB, 2)
                Manufacturer    = $vmHost.Manufacturer
                Model           = $vmHost.Model
                LicenseKey      = $vmHost.LicenseKey
                ProcessorType   = $vmHost.ProcessorType
                IsStandalone    = $vmHost.IsStandalone
                DatacenterName  = ($vmHost | Get-Datacenter).Name
                ClusterName     = ($vmHost | Get-Cluster).Name
            }

            # Try to retrieve the serial number via Get-View
            $serialNumber = $hostView.Hardware.SystemInfo.SerialNumber
            $hardwareInfo["SerialNumber"] = if (-not [string]::IsNullOrEmpty($serialNumber)) { $serialNumber } else { "Not Retrieved" }
        }
        catch {
            Write-Log -Message "Failed to retrieve data via Get-View for host $($vmHost.Name): $($_.Exception.Message)" -Level "Error"
        }

        # If the serial number was not retrieved, try to get it via ESXCLI without -V2
        if ($hardwareInfo["SerialNumber"] -eq "Not Retrieved") {
            try {
                $esxcli = Get-EsxCli -VMHost $vmHost
                $serialNumberCLI = $esxcli.hardware.platform.get().SerialNumber
                if (-not [string]::IsNullOrEmpty($serialNumberCLI)) {
                    $hardwareInfo["SerialNumber"] = $serialNumberCLI
                }
            }
            catch {
                Write-Log -Message "Failed to retrieve Serial Number via ESXCLI for host $($vmHost.Name): $($_.Exception.Message)" -Level "Warning"
            }
        }

        # Check license expiration status
        try {
            # Get License Manager and Assignment Manager
            $licenseMgr = Get-View -Id "LicenseManager"
            $licenseAssignmentMgr = Get-View $licenseMgr.LicenseAssignmentManager

            # Query the assigned license for the specific ESXi host
            $hostMoRef = $vmHost.ExtensionData.MoRef.Value
            $hostLicenseAssignments = $licenseAssignmentMgr.QueryAssignedLicenses($hostMoRef)

            # Filter the license assignment for the ESXi host
            if ($hostLicenseAssignments -and $hostLicenseAssignments.AssignedLicense) {
                $hostLicense = $hostLicenseAssignments.AssignedLicense
                $expirationProperty = $hostLicense.Properties | Where-Object { $_.Key -eq "expirationDate" } | Select-Object -ExpandProperty Value

                # Determine if the license is permanent or temporary based on expiration date
                if ([string]::IsNullOrEmpty($expirationProperty)) {
                    $licenseStatus = "Valid (Permanent)"
                }
                elseif ([datetime]::TryParse($expirationProperty, [ref]$null)) {
                    $expirationDate = [datetime]::Parse($expirationProperty)
                    if ($expirationDate -gt (Get-Date)) {
                        $licenseStatus = "Valid (Temporary)"
                    }
                    else {
                        $licenseStatus = "Expired"
                    }
                }
                else {
                    $licenseStatus = "Invalid Date Format"
                }
            }
            else {
                $licenseStatus = "No License Assigned"
            }

            $hardwareInfo["LicenseStatus"] = $licenseStatus
        }
        catch {
            Write-Log -Message "Failed to retrieve license information for host $($vmHost.Name): $($_.Exception.Message)" -Level "Warning"
        }

        return [PSCustomObject]$hardwareInfo
    }


  • 2.  RE: Get License information

    Posted Oct 30, 2024 12:57 PM

    Did you mix up the "Valid (Permanent)" and "Valid (Temporary)" licenses?
    When the $expirationProperty is empty it indicates a "Product Evaluation" license afaik.



    ------------------------------


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


    ------------------------------



  • 3.  RE: Get License information

    Posted Oct 31, 2024 07:52 AM

    I changed the approach and I'm able to get the required details:

    function Get-ESXiHostInventory {
        param (
            [Parameter(Mandatory = $true)]
            [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$vmHost
        )

        # Initialize hardware information variables and set default values
        $hardwareInfo = @{ }
        $serialNumber = "Not Retrieved"
        $licenseStatus = "Unknown"

        # Get basic hardware information via Get-View (vSphere API) for ESXi hosts
        try {
            $hostView = $vmHost | Get-View
            $totalCpuCores = $hostView.Hardware.CpuInfo.NumCpuCores

            $hardwareInfo = @{
                Hostname        = $vmHost.Name
                ConnectionState = $vmHost.ConnectionState
                PowerState      = $vmHost.PowerState
                CpuTotalGHz     = [math]::round(($hostView.Hardware.CpuInfo.Hz * $totalCpuCores) / 1e9, 2)
                CpuUsageGHz     = [math]::round($vmHost.CpuUsageMhz / 1000, 2)
                CpuCount        = $hostView.Hardware.CpuInfo.NumCpuPackages
                TotalCPUCores   = $totalCpuCores
                MemoryTotalGB   = [math]::round($vmHost.MemoryTotalGB, 2)
                MemoryUsageGB   = [math]::round($vmHost.MemoryUsageGB, 2)
                Manufacturer    = $vmHost.Manufacturer
                Model           = $vmHost.Model
                LicenseKey      = $vmHost.LicenseKey
                ProcessorType   = $vmHost.ProcessorType
                IsStandalone    = $vmHost.IsStandalone
                DatacenterName  = ($vmHost | Get-Datacenter).Name
                ClusterName     = ($vmHost | Get-Cluster).Name
            }

            # Retrieve Serial Number
            $serialNumber = $hostView.Hardware.SystemInfo.SerialNumber
            $hardwareInfo["SerialNumber"] = if (-not [string]::IsNullOrEmpty($serialNumber)) { $serialNumber } else { "Not Retrieved" }
        }
        catch {
            Write-Log -Message "Failed to retrieve data via Get-View for host $($vmHost.Name): $($_.Exception.Message)" -Level "Error" -NoConsoleOutput
        }

        # If the serial number was not retrieved, try to get it via ESXCLI
        if ($hardwareInfo["SerialNumber"] -eq "Not Retrieved") {
            try {
                $esxcli = Get-EsxCli -VMHost $vmHost
                $serialNumberCLI = $esxcli.hardware.platform.get().SerialNumber
                if (-not [string]::IsNullOrEmpty($serialNumberCLI)) {
                    $hardwareInfo["SerialNumber"] = $serialNumberCLI
                }
            }
            catch {
                Write-Log -Message "Failed to retrieve Serial Number via ESXCLI for host $($vmHost.Name): $($_.Exception.Message)" -Level "Warning" -NoConsoleOutput
            }
        }

        # Check license expiration status
        try {
            # Get License Manager and Assignment Manager
            $licenseMgr = Get-View -Id "LicenseManager"
            $licenseAssignmentMgr = Get-View $licenseMgr.LicenseAssignmentManager
            # Query the assigned license for the specific ESXi host
            $hostMoRef = $vmHost.ExtensionData.MoRef.Value
            $hostLicenseAssignments = $licenseAssignmentMgr.QueryAssignedLicenses($hostMoRef)
            # Filter the license assignment for the ESXi host
            if ($hostLicenseAssignments -and $hostLicenseAssignments.AssignedLicense) {
                $hostLicense = $hostLicenseAssignments.AssignedLicense
                $expirationProperty = $hostLicense.Properties | Where-Object { $_.Key -eq "expirationDate" } | Select-Object -ExpandProperty Value

                # Check if expirationDate is empty or needs to be parsed
                if ([string]::IsNullOrEmpty($expirationProperty)) {
                    $licenseStatus = "Permanent"
                }
                else {
                    try {
                        $expirationDate = [datetime]::ParseExact($expirationProperty, "MM/dd/yyyy HH:mm:ss", $null)
                        # Format the expiration status with date
                        if ($expirationDate -gt (Get-Date)) {
                            $licenseStatus = "Temporary (Expires on $($expirationDate.ToString('MM/dd/yyyy')))"
                        }
                        else {
                            $licenseStatus = "Expired (Expired on $($expirationDate.ToString('MM/dd/yyyy')))"
                        }
                    }
                    catch {
                        $licenseStatus = "Invalid Date Format"
                        Write-Log -Message "Error parsing date format for host $($vmHost.Name): $($_.Exception.Message)" -Level "Warning" -NoConsoleOutput
                    }
                }
            }
            else {
                $licenseStatus = "No License Assigned"
            }

            $hardwareInfo["LicenseStatus"] = $licenseStatus
        }
        catch {
            Write-Log -Message "Failed to retrieve license information for host $($vmHost.Name): $($_.Exception.Message)" -Level "Warning" -NoConsoleOutput
        }

        return [PSCustomObject]$hardwareInfo
    }


    Thank you @LucD

    How to mark the thread is solved ?



  • 4.  RE: Get License information

    Posted Oct 31, 2024 07:56 AM

    On someone's reply, there are 2 options, "Mark best answer" and "Close thread".
    Not sure if both are needed.



    ------------------------------


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


    ------------------------------