Automatically import KeyVault secrets as variables

I have PSU hooked up to an Azure KeyVault and creating variables in the UI works fine. I can see in the that you can import secret variables if they already exist in KeyVault, which also works if adding them via the UI however does anyone know if there is a way to programmatically import variables if the secrets are created in KV?
The method I was thinking of was to have a script on a schedule which looks up secrets in the KeyVault and then running a New-PSUVariable for each secret it finds using the name and value pulled back:

$KVSecrets=Get-AzKeyVaultSecret -VaultName $env:KeyVault_Name -WarningAction SilentlyContinue | Where-Object {$_.ContentType -eq "PSUSecret"}

foreach ($PSUSecret in $KVSecrets) {

    Write-output "Secret Found: $($PSUSecret.Name)"

    $SecretValue=(Get-AzKeyVaultSecret -Name $PSUSecret.Name -VaultName $env:KeyVault_Name).SecretValueText

    New-PSUVariable -Name $PSUSecret.Name -Vault "AzureKeyVault" -Value $SecretValue

}

I can see in the output that it gets the secrets but New-PSUVariable doesn’t seem to be creating them.

Does anyone know:
a) if this is even possible?
b) if there’s a better way - i.e. automatically import rather than create variables as in theory this is going to get the value back from KeyVault then overwrite it again in KeyVault with the same value which seems a bit long winded.

Thanks,
Tom.

Product: PowerShell Universal
Version: 2.11.1

Sorry I misunderstood the correct usage of the New-PSUVariable command.
I’ll leave this post in case anyone else has the same thought process though.

The command needs to sit inside the variables.ps1 file and calling it outside of this doesn’t do anything so to use this correctly you need to get the content of the file, check for a variable with the same name first then if it doesn’t exist, append the New-PSUVariable command as a new line in the file.

Here’s a basic example (not particularly elegant as it was just put together quickly to test functionality):

$VariableName="VariableName"
$Pattern='-Name "'+$VariableName+'"'

if (Select-String -Path $VariableFile -Pattern $Pattern) {
    Write-output "Variable already exists"
}
else {
    Write-output "Creating Variable $VariableName"
    $String='New-PSUVariable -Name "'+$VariableName+'" -Vault "AzureKeyVault"'
    Add-Content -Path $VariableFile -Value "`r`n$String" -NoNewline
}