I was watching a Pluralsight course this morning, and I came across the second instance of VBA-style string concatenation that I’d seen this week.
You know, like this:
$FirstName = "Joe"
$LastName = "Bloggs"
$DisplayName = $LastName + ", " + $FirstName
$UserName = $FirstName + "." + $LastName + "@globomantics.org"
This is one of my pet peeves, as it’s not necessary in PowerShell, and it makes the code harder to read.
PowerShell is quite capable of expanding variables within a string. This is called an ‘expanding string’:
$DisplayName = "$LastName, $FirstName"
$UserName = "$FirstName.$LastName@globomantics.org"
If you want to go one step farther, you can use the format operator:
$DisplayName = "{0}, {1}" -f $LastName,$FirstName
$UserName = "{0}.{1}@globomantics.org" -f $FirstName,$LastName
This allows for cleaner insertion of variables, especially if you want to do something like this to get rid of capital letters in an email address or UPN (another of my pet peeves):
$UserName = "{0}.{1}@globomantics.org" -f $FirstName.ToLower(),$LastName.ToLower()
Some good reading on the Hey, Scripting Guy! blog: