Public/Get-SfDevices.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<#
    .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
    }
}