Public/Get-SfDevices.ps1

<#
    .SYNOPSIS
    Queries salesforce for devices.

    .DESCRIPTION
    Used to query for devices in the salesforce org. Can query all devices or just devices for one patient.

    .INPUTS
    None. You cannot pipe objects to Get-SfDevices.

    .OUTPUTS
    An array of PSCustomObject with the properties:
        Id
        phecc__Device_ID__c
        phecc__Device_Master_Id__c
        phecc__Device_Model__c
        phecc__Patient__c
        phecc__Site_Name__c
        phecc__Site__c
        phecc__Replace_Request_Date__c

    .EXAMPLE
    PS> $devicesAssignedToPatients = Get-SfDevices | Where-Object {$_.phecc__Patient__c}

    .LINK
    Set-Config

    .NOTES
    Assumes config is initialized for org access.
#>

function Get-SfDevices {

    [CmdletBinding()]
    [OutputType([PSCustomObject[]])]
    param(
        [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline)]
        [ValidateNotNull()]
        [PSCustomObject]
        $Patient
    )

    begin {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Function started"
    }

    end {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Complete"
    }

    process {
        Write-Debug "[$($MyInvocation.MyCommand.Name)] PSBoundParameters: $($PSBoundParameters | Out-String)"

        $query = "SELECT Id,Name,phecc__Device_ID__c,phecc__Device_Master_Id__c,phecc__Device_Model__c,phecc__Patient__c,phecc__Site_Name__c,phecc__Site__c"

        # if the field "phecc__Replace_Request_Date__c" exists then include it in the query
        $describe = Get-SfSObjectDescribe "phecc__Device__c"
        $hasReplaceDateField = ($describe.fields | Where-Object { $_.name -eq "phecc__Replace_Request_Date__c" })
        if ($hasReplaceDateField) {
            $query += ",phecc__Replace_Request_Date__c"
        }
        $query += " FROM phecc__Device__c"
        if ($PSBoundParameters.ContainsKey('Patient')) {
            $query += " WHERE phecc__Patient__c = '$($Patient.sfPatient.Id)'"
        }
        $results = Invoke-SfQuery $query
        if (-not $hasReplaceDateField) {
            # add an empty so query results are consistient
            $results | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name "phecc__Replace_Request_Date__c" -Value $null }
        }
        Write-Output $results
    }
}