Wednesday, November 5, 2025

Powershell script to get Keyvault token using Powershell - Windows and Linux

 $os = [System.Environment]::OSVersion.Platform

$runningLinux = $false


$Host.UI.WriteLine("Running on $os")


if("Unix" -eq $os)

{

    $runningLinux = $true

}

az login --service-principal   -u <principle-guid>   -p <active-secret>   --tenant <token-guid>

$Host.UI.WriteLine("Login was successful for az cli and now going to get the token from https://vault.azure.net")

$token=az account get-access-token --resource https://vault.azure.net --query accessToken -o tsv


$Host.UI.WriteLine("Received token successful $token")

 

# Define headers properly (PowerShell expects a hash table)

$headers = @{

    "Authorization" = "Bearer $token"

}

 

$Host.UI.WriteLine("Start calling nslook on kvdmpprodae001.vault.azure.net")

if(!$runningLinux)

{

    Resolve-DnsName kvdmpprodae001.vault.azure.net

} else

{

    nslookup kvdmpprodae001.vault.azure.net

}

$Host.UI.WriteLine("End calling nslook on kvdmpprodae001.vault.azure.net")


$Host.UI.WriteLine("Start calling curl on https://kvdmpprodae001.vault.azure.net")

curl -v https://kvdmpprodae001.vault.azure.net

$Host.UI.WriteLine("End calling curl on https://kvdmpprodae001.vault.azure.net")

 

if($runningLinux)

{

    $Host.UI.WriteLine("Start calling curl on https://kvdmpprodae001.vault.azure.net/secrets/<your-key-name>?api-version=7.3")

    curl -v -H "Authorization: Bearer $token" --trace-ascii trace.log https://kvdmpprodae001.vault.azure.net/secrets/<your-key-name>?api-version=7.3

    $Host.UI.WriteLine("End calling curl on https://kvdmpprodae001.vault.azure.net/secrets/<your-key-name>?api-version=7.3")

}

 

# Call Key Vault REST API


$Host.UI.WriteLine("Invoking the webrequest with the token received")

$response = Invoke-WebRequest -Uri "https://kvdmpprodae001.vault.azure.net/secrets/<your-key-name>?api-version=7.3" -Headers $headers

 

    $Host.UI.WriteLine("Now printing the vault access")

# Output response

$response.Content



Once you created above .ps1 file. Run it using Powershell in Windows or install powershell in Linux and run using :

pwsh <filename>.ps1

No comments: