Microsoft Azure Foundry gives you pay-per-token models (Mistral, Claude, Llama, DeepSeek and many more). There's no VM or container to deploy, no expensive infrastructure to manage. You call an API endpoint and pay for the tokens you use.
That changes what a script can do. Most automation is deterministic: if the input matches a known case, the code handles it. When the input is ambiguous, or a case was never written into the code base, a script can now hand that part to a model and get back an answer it can act on.
Getting started is easy. Pick a model, and Foundry gives you an endpoint and a key. The portal even generates sample code in Python, JavaScript, Go, C# and Java. There's no PowerShell sample, though.
But it doesn’t mean you can’t use it with PowerShell. In this post I show how to:
- get the endpoint and the key to a Foundry resource
- list the models you can deploy, and the ones already deployed
- deploy a model
- chat with a model, stream its answer, and keep a conversation history
- use a decision model to get typed answers instead of text
What you need is PowerShell 7.x, Az.Account module and an Azure Subscription.
Create the Foundry resource and project
Go to https://ai.azure.com and make sure the new Foundry experience is selected. This post doesn't work with classic serverless deployments. Create a project, then choose the subscription, the resource group and the region. The region decides which models you can deploy.
Next, check the roles. You need Cognitive Services Contributor (or Foundry Account Owner) on the Foundry resource to read the keys and deploy models. With an API key, the inference calls themselves don't need any role. If you call the models with a Microsoft Entra ID token instead of a key, you also need Foundry User (previously Azure AI User). To consume model, you only need the role Cognitive Services User.
Management plane and data plane
Working with Foundry means talking to two APIs:
- the management plane (Azure Resource Manager) to find the endpoint, read the keys, list models and manage deployments
- the data plane (the Foundry endpoint) to send prompts to the models
Get the endpoint and the key
Start with an ARM token, then read the Foundry resource to get its endpoint and keys.
$armToken = (Get-AzAccessToken -ResourceUrl 'https://management.azure.com').Token
$armApi = '2025-06-01'
$group = "https://management.azure.com/subscriptions/<SubID>/resourceGroups/<FoundryRG>"
$account = "$group/providers/Microsoft.CognitiveServices/accounts/<FoundryResourceName>"
$resource = Invoke-RestMethod -Uri "${account}?api-version=${armApi}" -Authentication Bearer -Token $armToken
$endpoint = $resource.properties.endpoints.'AI Foundry API'.TrimEnd('/')
$keys = Invoke-RestMethod -Method Post -Uri "${account}/listKeys?api-version=$armApi" `
-Authentication Bearer -Token $armToken
$apiKey = ConvertTo-SecureString $keys.key1 -AsPlainText -Force
$endpoint and $apiKey are all you need to call the models deployed in this Foundry resource.
$catalog = Invoke-RestMethod -Uri "${account}/models?api-version=${$armApi}" -Authentication Bearer -Token $armToken
$catalog.value |
Where-Object { $_.capabilities.chatCompletion -eq 'true' -and $_.isDefaultVersion } |
Where-Object lifecycleStatus -NE 'Deprecated' |
Sort-Object format, name |
Format-Table format, name, version, lifecycleStatus
This lists the chat models you can deploy in this Foundry resource. The list depends on its Azure region.
List the models already deployed
$deployments = (Invoke-RestMethod -Uri "${account}/deployments?api-version=$armApi" -Authentication Bearer -Token $armToken).value
$deployments | ForEach-Object {
[pscustomobject]@{
Name = $_.name
Model = $_.properties.model.name
Sku = $_.sku.name
Capacity = $_.sku.capacity
State = $_.properties.provisioningState
}
} | Format-Table
Deploy a model
Deploying a model is also a management plane operation, so the identity running the script needs Cognitive Services Contributor. The ARM token in $armToken is short-lived (about an hour), so refresh it before a long operation.
The following script deploys mistral-small-2503 in the Foundry resource.
# refresh the ARM Token
$armToken = (Get-AzAccessToken -ResourceUrl 'https://management.azure.com').Token
$deploymentName = 'article-mistral-small'
$deploymentUri = "${account}/deployments/${deploymentName}?api-version=$armApi"
$body = @{
sku = @{ name = 'GlobalStandard'; capacity = 5 } # 5 requests and 5000 tokens per minute
properties = @{ model = @{ format = 'Mistral AI'; name = 'mistral-small-2503'; version = '1' } }
} | ConvertTo-Json -Depth 5
$deployment = Invoke-RestMethod -Method Put -Uri $deploymentUri -Authentication Bearer -Token $armToken -ContentType 'application/json' -Body $body
# the deployment can take several minutes
for ($poll = 1; $deployment.properties.provisioningState -notin 'Succeeded', 'Failed', 'Canceled'; $poll++) {
if ($poll -gt 60) { throw "$deploymentName is still $($deployment.properties.provisioningState) after 5 min." }
Start-Sleep -Seconds 5
$deployment = Invoke-RestMethod -Uri $deploymentUri -Authentication Bearer -Token $armToken
}
if ($deployment.properties.provisioningState -ne 'Succeeded') { throw "Deployment $deploymentName failed." }
Chat with a model
Time for the first conversation with a model. The model field takes the deployment name. For the chat examples I use a Mistral-Large-3 deployment.
$body = @{
model = "Mistral-Large-3"
max_tokens = 200
messages = @(
@{ role = 'user'; content = 'In one sentence, what is Azure AI Foundry?' }
)
} | ConvertTo-Json -Depth 5 # the default depth (2) silently truncates nested objects
$response = Invoke-RestMethod -Method Post -Uri "$endpoint/openai/v1/chat/completions" `
-Authentication Bearer -Token $apiKey -ContentType 'application/json' -Body $body
# the model response
$response.choices[0].message.content
# Tokens used during the interaction
$response.usage
Stream the response
For long answers you can stream the response and read it line by line while the model generates it. Invoke-RestMethod waits for the whole HTTP response before returning, so streaming needs System.Net.Http.HttpClient.
$body = @{
model = $chatModel
stream = $true
max_tokens = 200
messages = @(@{ role = 'user'; content = 'Write a haiku about PowerShell.' })
} | ConvertTo-Json -Depth 5
$client = [System.Net.Http.HttpClient]::new()
$request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post,
"$endpoint/openai/v1/chat/completions")
# HttpClient wants the key as a plain string
$request.Headers.Add('api-key', [System.Net.NetworkCredential]::new('', $apiKey).Password)
$request.Content = [System.Net.Http.StringContent]::new($body, [System.Text.Encoding]::UTF8, 'application/json')
# ResponseHeadersRead: return as soon as the headers arrive, without buffering the body
$option = [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead
$response = $client.SendAsync($request, $option).GetAwaiter().GetResult()
$null = $response.EnsureSuccessStatusCode()
$reader = [System.IO.StreamReader]::new($response.Content.ReadAsStream())
while ($null -ne ($line = $reader.ReadLine())) {
if (-not $line.StartsWith('data: ')) { continue } # events are separated by blank lines
$data = $line.Substring(6)
if ($data -eq '[DONE]') { break }
$text = ($data | ConvertFrom-Json).choices[0].delta.content
if ($text) { Write-Host $text -NoNewline }
}
# cleanup
$reader.Dispose(); $response.Dispose(); $request.Dispose(); $client.Dispose()
Keep a conversation history
Each call to a model is independent. The model has no memory, so the caller must send the whole history every time. The order of the messages matters, so use an ordered collection such as System.Collections.Generic.List[hashtable].
$history = [System.Collections.Generic.List[hashtable]]::new()
$history.Add(@{ role = 'system'; content = 'You are a concise travel guide.' })
foreach ($question in 'I am going to Paris, what should I see?', 'What is so great about #2?') {
$history.Add(@{ role = 'user'; content = $question })
$body = @{
model = $chatModel
messages = $history
max_tokens = 400
temperature = 0.8 # the accepted range depends on the model (Mistral: 0 to 1)
top_p = 0.1
} | ConvertTo-Json -Depth 5
$response = Invoke-RestMethod -Method Post -Uri "$endpoint/openai/v1/chat/completions" `
-Authentication Bearer -Token $apiKey -ContentType 'application/json' -Body $body
$answer = $response.choices[0].message
$history.Add(@{ role = $answer.role; content = $answer.content })
"> $question`n$($answer.content)`n"
}
Use a decision model
The last thing to explore is decision models. Since JEV came out in September 2026, Foundry offers models that return a typed answer instead of a conversation. I wrote about JEV in JEV gives you probabilities, not decisions.
A decision model accepts three types of question:
- noul: a yes/no question, answered with a probability
- choice: pick one option from a list
- score: rank the input on an ordered scale
Foundry has several decision models. I use the latest one from Microsoft, Microsoft-Decision-1.1.
The first example checks whether a message is urgent.
$body = @{
model = $decisionModel
state = 'The payment integration still fails. Please help today.'
questions = @{ urgent = @{ type = 'noul'; instructions = 'Does this message convey urgency?' } }
} | ConvertTo-Json -Depth 5
$result = Invoke-RestMethod -Method Post -Uri "$endpoint/providers/microsoft/v1/systemone" `
-Authentication Bearer -Token $apiKey -ContentType 'application/json' -Body $body
"Probability that the message is urgent: $($result.answers.urgent.noul)"
The result, Probability that the message is urgent: 0.996770198110101, is a clear yes.
The second example uses all three question types to triage support tickets from a CSV: is the ticket urgent, which team should handle it, and what priority should it get?
$tickets = @'
Id,Text
101,"Production is down since 8am, our customers cannot pay. Call me now!"
102,"Could you send me the price list for the enterprise plan?"
103,"I was charged twice for my invoice of October."
104,"Small typo on the login page, no rush."
'@ | ConvertFrom-Csv
$questions = [ordered]@{
urgent = @{ type = 'noul'; instructions = 'Does this message convey urgency?' }
team = @{ type = 'choice'; criteria = [ordered]@{ billing = 'Billing'; tech = 'Technical'; sales = 'Sales' } }
priority = @{ type = 'score'; criteria = @('low', 'medium', 'high') }
}
$triage = foreach ($ticket in $tickets) {
$body = @{ model = $decisionModel; state = $ticket.Text; questions = $questions } | ConvertTo-Json -Depth 5
$answers = (Invoke-RestMethod -Method Post -Uri "$endpoint/providers/microsoft/v1/systemone" `
-Authentication Bearer -Token $apiKey -ContentType 'application/json' -Body $body).answers
# score: probabilities and legend are keyed by level index ("0", "1", "2")
$level = $answers.priority.probabilities.PSObject.Properties |
Sort-Object Value -Descending | Select-Object -First 1
[pscustomobject]@{
Id = $ticket.Id
Urgent = [math]::Round($answers.urgent.noul, 2)
Team = $answers.team.choice
Priority = $answers.priority.legend.($level.Name)
Text = $ticket.Text
}
}
$triage | Sort-Object Urgent -Descending | Format-Table
The result:
Triage table: ticket ID, urgency probability, team and priority for the four sample tickets.
Each answer is a typed value your script can branch on, with no parsing of free text.
Wrapping up
Using Foundry from PowerShell means handling two APIs, the management plane and the data plane, with raw Invoke-RestMethod calls. That's fine for a small project, but at scale the boilerplate gets error-prone: token refresh, deployment names, request bodies, response parsing.
I started a PowerShell module to cover this: pwsh-azurefoundry. Feedback and contributions are welcome.


Top comments (0)