Powershell – Saving an Azure SAS Token URI to a file in Powershell

azurepowershell

I need to write the full URI of an Azure storage blob – with a SAS token – from a variable into a file, and read it out on a subsequent run of a script (on the other side of a reboot). Because SAS token URIs contain at least a single ampersand, the variable output into the file is getting truncated at the first one;

$sasTokenURI | out-file "c:\sasTokenURI.txt"

Writes the URI up to and excluding the first ampersand.

How can I force Powershell to verbatim output the URI to a file and then read it verbatim in later?

Best Answer

I am not sure my understanding is right, if my answer has some wrong please point me. The following step works for me, maybe you could check.

$StorageAccountName = "shuilinuxdiag336"
$StorageAccountContext = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -eq $StorageAccountName}).Context
$StorageContainerName = "customscriptfiles"

$StartTime = Get-Date
$EndTime = (Get-Date).AddHours(4)
$blobName = "install_nginx_ubuntu.sh"
$SASURI = New-AzureStorageBlobSASToken -Container $StorageContainerName `
    -Blob $blobName `
    -Context $StorageAccountContext `
    -Permission "rwd" `
    -StartTime $StartTime `
    -ExpiryTime $EndTime `
    -FullUri

$SASURI | out-file "C:\Users\v-shshui\test.txt"

$sasTokenURI = cat "C:\Users\v-shshui\test.txt"

Invoke-WebRequest -Uri $sasTokenURI -OutFile $blobName

I test in my lab, it works for me.

enter image description here