How to clean up the FHIR objects using bundle in PowerShell?

Summary

This post is continuation of the previous post.

How to clean up the FHIR objects in the Postman received as a bundle?

PowerShell Code

# Load the System.Web assembly
Add-Type -AssemblyName System.Web

# Define the OAuth 2.0 endpoint and client credentials
$clientId = "<YOUR-CLIENT-ID>"
$clientSecret = "<YOUR-CLIENT-SECRET"
$tenantId="<YOUR-TENANT-ID>"
$fhirurl = "https://<YOUR-FHIR-SERVICE>.fhir.azurehealthcareapis.com/"

$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token"


# Create the body for the token request
$body = @{
    grant_type = "client_credentials"
    client_id = $clientId
    client_secret = $clientSecret
    resource = $fhirurl
}

# Convert the body to a URL-encoded string
$bodyEncoded = [System.Web.HttpUtility]::ParseQueryString([System.String]::Empty)
$body.GetEnumerator() | ForEach-Object { $bodyEncoded.Add($_.Key, $_.Value) }
$bodyString = $bodyEncoded.ToString()

# Make the token request
$response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $bodyString

# Extract the access token from the response
$accessToken = $response.access_token

# Use the access token to make an API call
$apiUrl = "$fhirurl/Condition?_elements=fullurl&_count=500"
$headers = @{
    Authorization = "Bearer $accessToken"
}

# Make the API request
$apiResponse = Invoke-RestMethod -Method Get -Uri $apiUrl -Headers $headers

# Output the API response
$apiResponse

# Check if the count of entries is greater than zero
if ($apiResponse.entry.Count -gt 0) {
    # Create the entries array dynamically
    $entries = @()
    foreach ($anEntry in $apiResponse.entry) {
        $entry = @{
            request = @{
                method = "DELETE"
                url = $anEntry.fullUrl
            }
        }
        $entries += $entry
    }

    # Define the JSON structure
    $jsonData = @{
        resourceType = "Bundle"
        type = "transaction"
        entry = $entries
    }

    # Convert the PowerShell object to JSON
    $jsonString = $jsonData | ConvertTo-Json -Depth 3

    # Output the JSON string
    #$jsonString


    # Send the POST request with the JSON string as the body
    try {


        $postResponse = Invoke-RestMethod -Method Post -Uri $fhirurl -Headers $headers -Body $jsonString -ContentType "application/json"

        # Output the response from the POST request
        #$postResponse
    } 
    catch 
    {
        Write-Error "Failed to send POST request: $_"
    } 
}
else {
    <# Action when all if and elseif conditions are false #>
    Write-Output "There are no items left."
}

Conclusion

This is other ways you can clean up the FHIR objects.

Unknown's avatar

About Pankaj

I am a Developer and my linked profile is https://www.linkedin.com/in/pankajsurti/
This entry was posted in FHIR and tagged , , , , . Bookmark the permalink.

Leave a comment