使用powershell在单引号中展开此处字符串中的变量

mccptt67  于 2023-02-16  发布在  Shell
关注(0)|答案(1)|浏览(188)

我有一个场景,我使用了带单引号的here-string,因为我需要打印变量,同时还需要扩展其中的某些变量。你能建议我如何实现这一点吗?

$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"
'@

此处字符串的实际值应如下所示:

$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"
wljmcqd8

wljmcqd81#

您可以为此使用ExecutionContext ExpandString。
你的困难在于“expandcertainvariables"。这意味着你需要区分你想扩展的变量和你想转义的变量(用反勾号:``$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

相关问题