Ninja Nichols

The discipline of programming

PowerShell Variable Followed by Colon

I’ve got a little PowerShell script that writes some configuration settings. In it there’s a line that computes a certain URL for a given subdomain:

$url = "http://$subdomain.ninjanichols.com:8080/"

Pretty standard stuff. But something interesting happens when you try to generalize it and make the domain itself variable:

$url = "http://$subdomain.$domain:8080/"

Instead of http://sub.ninjanichols.com:8080/, I get http://sub./. What’s going on?

Turns out the colon has a special meaning in PowerShell, it’s used both to specify items on a PSDrive, $Env:Foo, or to associate a variable with a scope or namespace, $global:var. So when PowerShell tries to interpret $domain:8080 it sees one variable, instead of a variable + a string.

How to fix it? Just make the intention clear using curly brackets:

$url = "http://${subdomain}.${domain}:8080/"