At the minute I'm working on storing and retrieving secrets, specifically from Hashicorp Vault. Vault is cool since it has an API that I can access using Invoke-RestMethod without messing about with a bunch of modules. Also cool is the fact that you get your secrets back as a chunk of json.

An issue came up where I wanted to retrieve a wad of json formatted secrets and set them as variables. Took me a few tries to figure it out, but I got some simple code working and thought I'd post it here in case I need it again.

The snippet below generates some fake json just for the purposes of the test, normally you'd get this json from a file or API output. We convert the json to a PSObject, get the properties of that object, then iterate on the list of properties to make new variables using New-Variable, which lets us set the name of our new variable as a variable.

Man it's hard to type 'variable' a bunch of times and feel like it makes sense. Anyway, here's the code...

# Create some fake json 
$jsonLikeObject = @{
    value1 = "This is a secret!"
    value2 = "This=too,isAs3crt"
$json = ($jsonLikeObject | ConvertTo-Json)

# The real stuff!

# Convert the json to a PSObject
$namesAndValues = $json | ConvertFrom-Json
# Get the list of properties
$varNames = $

# For each property, create a var with its name and corresponding value
ForEach ($variable in $varNames) {
    New-Variable -Name $variable -Value $namesAndValues.$variable -Force

# Prove it!
Write-Output $value1
Write-Output $value2

Woo! Now I can run this snippet and have all the variables in my json populated for me :)

If you're feeling spicy, you could change the New-Variable line to read Set-Item "Env:$variable" -Value $namesAndValues.$variable and set them as environment variables.