Home > Net >  Expand variable within here-string in single quote using powershell
Expand variable within here-string in single quote using powershell

Time:02-02

I have a scenario where I am using here-string with single quotes since I need to print the variable as it is and also expand certain variables within it. Can you please suggest how I can achieve this?

$S3BucketName = "Dynamically generated"
$file = "Dynamically generated" 

#This is for remote execution
$UserDataInput = @'
$Instance = "Dynamically generated"
Read-S3Object -BucketName $S3BucketName -Key "Path\$file.pem" -File "C:\Temp\$file.pem"
$Pass=Get-EC2PasswordData -InstanceId $Instance -PemFile "C:\Temp\$file.pem"
'@

The actual value of here string should look as below:

    $Instance = "Dynamically generated"
    Read-S3Object -BucketName testbucket -Key "Path\testfile.pem" -File "C:\Temp\testfile.pem"
    $Pass=Get-EC2PasswordData -InstanceId $Instance -PemFile "C:\Temp\testfile.pem"

CodePudding user response:

You can use ExecutionContext ExpandString for this.
The difficulty thou, is in the "expand certain variables". Meaning that you will need to differentiate between the ones you want to expand and the ones you want to escape (with a backtick: `$DontExpand):

$S3BucketName = "MyBucket"
$file = ".\MyFile.pem" 

#This is for remote execution
$UserDataInput = @'
`$Instance = "Dynamically generated"
Read-S3Object -BucketName $S3BucketName -Key "Path\$file.pem" -File "C:\Temp\$file.pem"
`$Pass=Get-EC2PasswordData -InstanceId `$Instance -PemFile $file
'@

 $ExecutionContext.InvokeCommand.ExpandString($UserDataInput)
$Instance = "Dynamically generated"
Read-S3Object -BucketName MyBucket -Key "Path\.\MyFile.pem.pem" -File "C:\Temp\.\MyFile.pem.pem"
$Pass=Get-EC2PasswordData -InstanceId $Instance -PemFile .\MyFile.pem
  • Related