Public/Get-Patients.ps1

<#
    .SYNOPSIS
    Returns a selected subset of patients in a Salesforce org.
 
    .DESCRIPTION
    Queries for Salesforce patients and queires the associated CDR resources for those patients.
 
    .INPUTS
    None. You cannot pipe objects to Get-Patients.
 
    .OUTPUTS
    An array of hashtables. Each hashtable contains the following keys:
        - sfPatient - the salesforce patient object
        - cdrPatient - the FHIR resource from PDS or CDR
 
    .PARAMETER SelectCdrIds
    An array of CDR ids to retrieve.
 
    .PARAMETER Status
    Only return patients with this status. Defaults to "Active"
    Can pass $null for all patients regardless of status.
 
    .PARAMETER Prompt
    If specified will display an interactive UI to select one or more patients. Default is not not prompt.
 
    .EXAMPLE
    PS> $patients = Get-Patients -Prompt -Status $null
 
    .LINK
    Set-FileConfig
 
    .NOTES
    Assumes config is initialized for org access.
#>

function Get-Patients {
    param(
        [String[]]$SelectCdrIds,
        [String]
        $Status = "Active",
        [Switch]
        $Prompt = $false
    )

    $sfPatients = Get-SfPatients -Status $Status
    if ($null -eq $sfPatients) {
        Write-Error "There are no patients of status '$($Status)' the org"
    }
    $cdrIds = @($sfPatients | Select-Object phecc__CDRPID__c -ExpandProperty phecc__CDRPID__c)
    $bundle = Get-CdrPatients $cdrIds
    $cdrPatients = $bundle.entry | Select-Object resource

    $selected = &{
        if ($SelectCdrIds) {
            $cdrPatients | Where-Object { $SelectCdrIds.Contains($_.resource.Id) } | Select-Object -ExpandProperty resource | Select-Object -Expandproperty id
        } elseif ($Prompt) {
            ($cdrPatients | ForEach-Object { $_.resource } | Select-Object id,@{Name='family';expression={($_.name | Where-Object {$_.use -eq 'usual'}).family}},@{Name='given';expression={($_.name | Where-Object {$_.use -eq 'usual'}).given}},birthDate) | Out-GridView -PassThru | Select-Object Id -ExpandProperty Id
        } else {
            $cdrPatients | Select-Object -ExpandProperty resource | Select-Object -Expandproperty id
        }
    }
    @($selected | ForEach-Object {
        $cdrId = $_
        @{
            sfPatient=($sfPatients | Where-Object {$_.phecc__CDRPID__c -eq $cdrId})
            cdrPatient=($cdrPatients | Where-Object {$_.resource.id -eq $cdrId})
        }
    })
}