Public/Invoke-CitrixMachinesApi.ps1

<#
.SYNOPSIS
    Fetches machine details from a Citrix Delivery Controller based on their lifecycle state and further filters for OS type based on machine type.
 
.DESCRIPTION
    This function queries for machines categorized either as Desktops or App Servers from a specified Citrix Delivery Controller.
    If 'Desktops' are queried, it filters for machines running Windows 10 or 11. For 'AppServers', it includes all other OS types.
 
.PARAMETER DeliveryController
    The hostname or IP address of the Citrix Delivery Controller from which to fetch the machine details.
 
.PARAMETER MachineType
    The type of machine to query: 'Desktops' or 'AppServers'.
 
.EXAMPLE
    Invoke-CitrixMachinesApi -DeliveryController "deliverycontroller.example.com" -MachineType 'Desktops'
    This example fetches details of Desktops running Windows 10 or 11 from the specified Delivery Controller.
 
.NOTES
    Requires Citrix PowerShell SDK and appropriate administrative credentials.
     
#>

function Invoke-CitrixMachinesApi {

    [CmdletBinding()]
    [OutputType('PSCustomObject')]
    param(
        [Parameter(Mandatory = $true)]
        [string] $DeliveryController,
        
        [Parameter(Mandatory = $true)]
        [ValidateSet('Desktops', 'AppServers')]
        [string] $MachineType
    )

    # Helper function to invoke REST query
    $invokeRestQuery = {
        param($Uri)
        try {
            $response = Invoke-RestMethod -Uri $Uri -UseDefaultCredentials -ContentType "application/json" -ErrorAction Stop
            return $response.value  # Directly return the 'value' property of the JSON response
        } catch {
            Write-Error "Failed to invoke REST query: $($_.Exception.Message)"
            return $null
        }
    }

    # Construct URI for API request to fetch machines based on query
    $Query = "`$select=HostedMachineId,OSType,HostingServerName,DnsName,IsInMaintenanceMode,AgentVersion,DesktopGroupId&`$filter=(LifecycleState eq 0) and (DesktopGroupId ne null) and (HostedMachineId ne null)"
    $machinesUri = "http://$DeliveryController/Citrix/Monitor/OData/v3/Data/Machines?`$format=json&$Query"

    # Fetch the machine details
    $machines = & $invokeRestQuery $machinesUri

    # Apply conditional filtering based on MachineType
    $filteredMachines = $machines | Where-Object {
        if ($MachineType -eq 'Desktops') {
           $_.OSType -eq 'Windows 10' -or $_.OSType -eq 'Windows 11'
        } else {
            $_.OSType -ne 'Windows 10' -and $_.OSType -ne 'Windows 11'
        }
    }

    # Return the filtered list
    return $filteredMachines
}