Hi,
Below is sample code to retrieve a secret using PowerShell running inside of vm using system managed identity. I modified this sample to create it.
$vaultUri = "https://mykeyvault.vault.azure.net"
$secretName = "testsecretname"
$response = Invoke-WebRequest -Uri "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=$vaultUri" -Headers @{Metadata="true"}
$access_token = ($response.Content|ConvertFrom-Json).access_token
$requestUri = $vaultUri + "/secrets/" + $secretName + "?api-version=7.4"
$vaultResponse = (Invoke-WebRequest -Uri $requestUri -Method GET -ContentType "application/json" -Headers @{Authorization ="Bearer $access_token"}).content
$secretValue = ($vaultResponse|ConvertFrom-Json).value
echo $secretValue
NOTE: for the above sample you need to enable the System Managed Identity on the VM via its Identity blade, and on your key vault the managed identity needs to be assigned Key Vault Secrets User role. The key vault access configuration needs to be set to Azure role-based access control.
Alternatively you can use vault access policy mode if you prefer (from your description it sounds like that is what you are using) just make sure to grant the managed identity permission to secrets.
Please click Accept Answer and upvote if the above was helpful. If something is unclear please add a comment below.
Thanks.
-TP