Using Azure PowerShell
I'd like to offer a another way to solve this, using an as close to pure Azure PowerShell as I could manage to find. It still relies on composing an Azure "Operation" but can be done in only a few lines of code.
Note: This assumes that you have a PowerShell session that is already authenticated. If you do not see: Connect-AzAccount for more information.
Option 1 - Retrieve key for function app for use with all functions
This example is based on this operation: Web Apps - List Host Keys and using this PowerShell cmdlet to execute the operation: Invoke-AzRestMethod
## lookup the resource id for your Azure Function App ##
$resourceId = (Get-AzResource -ResourceGroupName $rg -ResourceName $functionAppName -ResourceType "Microsoft.Web/sites").ResourceId
## compose the operation path for listing keys ##
$path = "$resourceId/host/default/listkeys?api-version=2021-02-01"
## invoke the operation ##
$result = Invoke-AzRestMethod -Path $urlPath -Method POST
if($result -and $result.StatusCode -eq 200)
{
## Retrieve result from Content body as a JSON object ##
$contentBody = $result.Content | ConvertFrom-Json
## Output the default function key. In reality you would do something more ##
## meaningful with this ##
Write-Host $contentBody.functionKeys.default
}
Option 2 - Retrieve a key for a specific function
This example is based on this operation to retrieve a key specific to the function. This is generally better practice so that you don't have a one-key for all functions. But there are valid reasons why you might want either. See this operation here: Web Apps - List Function Keys
## Lookup function name here ##
$functionName = "MyFunction"
## lookup the resource id for your Azure Function App ##
$resourceId = (Get-AzResource -ResourceGroupName $rg -ResourceName $functionAppName -ResourceType "Microsoft.Web/sites").ResourceId
## compose the operation path for listing keys ##
$path = "$resourceId/functions/$functionName/listkeys?api-version=2021-02-01"
## invoke the operation ##
$result = Invoke-AzRestMethod -Path $urlPath -Method POST
if($result -and $result.StatusCode -eq 200)
{
## Retrieve result from Content body as a JSON object ##
$contentBody = $result.Content | ConvertFrom-Json
## Output the default function key. In reality you would do something more ##
## meaningful with this. ##
Write-Host $contentBody.default
}