Using PowerShell 7 to Stream Responses from HttpRequests

Defining Script Behavior

$ProgressPreference = 'SilentlyContinue'
$ErrorActionPreference = 'Stop'

Method 1

# Create HttpClient
$client = [System.Net.Http.HttpClient]::new()

# Set the API request URL
$url = "https://graph.microsoft.com/v1.0/devices"

# Send the request and get the response as a stream
$response = $client.GetStreamAsync($url).Result

# Process the stream in chunks (for example, you can parse the JSON incrementally here)
$jsonReader = New-Object System.IO.StreamReader($response)
while (($line = $jsonReader.ReadLine()) -ne $null) {
    # Process each line or chunk of data here
    Write-Host $line
}

Method 2

# Define the function that handles data fetching and processing
function Get-DeviceData {
    $url = "https://graph.microsoft.com/v1.0/devices"
    $client = [System.Net.Http.HttpClient]::new()
    $response = $client.GetStreamAsync($url).Result

    $jsonReader = New-Object System.IO.StreamReader($response)
    while (($line = $jsonReader.ReadLine()) -ne $null) {
        # Process each line and update your GUI here
        Write-Host $line
    }
}

# Start the job asynchronously
$job = Start-Job -ScriptBlock {
    Get-DeviceData
}

# Wait for the job to finish (optional)
$job | Wait-Job
$job | Receive-Job

Method 3

# Define the function to handle the async request
function Get-DeviceDataAsync {
    $url = "https://graph.microsoft.com/v1.0/devices"
    $client = [System.Net.Http.HttpClient]::new()

    # Perform async operation
    return $client.GetStreamAsync($url)
}

# Use Start-Job to run the function asynchronously
$job = Start-Job -ScriptBlock {
    $task = Get-DeviceDataAsync
    $task.Result # Waits for the task to complete and gets the result
}

# You can continue to do other things in the UI while the job runs
Write-Host "Async task running in the background..."

# Optionally wait for the job to finish and get the result
$job | Wait-Job
$job | Receive-Job
Edit

Pub: 11 Jan 2025 20:35 UTC

Views: 9