Non Sequitur: Creating Dynamic Variables on the Fly in PowerShell

I’m only mentioning this because of something that came up recently and I thought it was kind of neat.

To keep things simple, I’m going to break this up into a few posts:

  1. Batch
  2. VBScript
  3. PowerShell


In the last 3 years or so I’ve tried to focus exclusively on PowerShell.  I’m no Jeff Snover, Dan Cunningham or any other PoSh guru you might know.  It’s still very new to me but I’m slowly working at it – so bear with me!

If you read my last two posts on this subject, you’ll know that I was all about creating variables dynamically for various reasons. I started each post the same:

I’m only mentioning this because of something that came up recently…

So here’s that something.

I had a repetitive task that involved doing something in a specific order so I challenged myself to create jobs and have the script wait for those jobs to finish before moving on.  I wanted a way to create a unique enough variable name for the jobs to help keep track of what was going on.  This is what really sparked that whole trip down memory lane of creating variables dynamically, on the fly, and I wanted to see if I could do it in PowerShell.

This is what I ended up with:

[array]$Colors = @('Blue','Black','Silver','Yellow','Orange')
Foreach($Color in $Colors)
        $varName = '$Paint_' + $Color
        write-host "varName [$varName]"

        $tmpVar = $varName + ' = "Paint this car [' + $Color + ']"'
        write-host "tmpVar [$tmpVar]"

        Invoke-Expression $tmpVar
        Invoke-Expression $varName
Remove-Variable varName,tmpVar -force -ea silentlycontinue
Get-Variable Paint_*

This allowed me to retrieve the individual jobs via $Paint_Color which was really useful for the task at hand as it had about 6 different moving parts some of which were dependencies.

Anyway, maybe you’ll find an application for this in your environment and if you do, I’d really like to hear about it.


Good Providence!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s