0

How can I expand all variables in a $scriptblock without manually writing out all variables:

I like to do it like this:

>>$scriptBlock = {Install-Package -Name $($Using:h.Name) \
>>  -RequiredVersion $($Using:h.Version) \
>>  -Source $Using:nuget_source -Force -SkipDependencies}
>>write-host ("install-command: {0}" -f $scriptBlock)

install-command: Install-Package -Name $($Using:h.Name) \
  -RequiredVersion $($Using:h.Version) -Source $Using:nuget_source \
  -Force -SkipDependencies

But I have to do it like this, which will make it hard to automate:

>>write-host ("install-command: Install-Package -Name {0} -RequiredVersion {1} -Source {2} -Force -SkipDependencies" \
>>  -f $h.Name, $h.Version, $nuget_source)

install-command: Install-Package -Name Selenium.WebDriver.IEDriver \
  -RequiredVersion 3.150.1 -Source https://nuget.org/api/v2/ -Force -SkipDependencies

The answer in powershell expand variable in scriptblock does not help because it is already a scriptblock:

>> [Scriptblock]$sb = [ScriptBlock]::Create($testScriptBlock)
>> $sb
Install-Package -Name $($Using:h.Name) -RequiredVersion \ 
   $($Using:h.Version) -Source $Using:nuget_source -Force -SkipDependencies
MortenB
  • 2,749
  • 1
  • 31
  • 35

1 Answers1

1

The $Using: is only available in sessions (About Using). Maybe you can convert the scriptblock to string and replace $Using: with $ and expand it.

write-host ("install-command: {0}" -f $ExecutionContext.InvokeCommand.ExpandString($scriptBlock.ToString().Replace('$Using:', '$')) )
Patrick
  • 2,128
  • 16
  • 24