THE SQL Server Blog Spot on the Web

Welcome to - The SQL Server blog spot on the web Sign in | |
in Search

The Rambling DBA: Jonathan Kehayias

The random ramblings and rantings of frazzled SQL Server DBA

Concatenating Powershell Strings

While catching up on blog comments while I was out I found on my blog post Reinventing the Wheel – Automating Data Consistency Checks with Powershell, a comment was posted by Grant regarding how I had concatenated the $ScriptName variable into the email subject line in the $subject variable.

Grant said:

Shouldn't the line

   $subject = "$ScriptName returned results"


   $subject = $ScriptName + " returned results" 

In TQL, you would have to do a + based concatenation like Grant asked, but in Powershell, its not necessary.  Take for example the following:

$string1 = "String1";
$string2 = "$String1 concatenated with String2";
Write-Host $string2;

The output will be:

String1 concatenated with String2

Does it really matter?  No, its pretty semantic.  You could also use the Format() method of the String Object in the .NET model to accomplish the same thing if you were so inclined:

$string1 = "String1";
$string2 = [String]::Format("{0} concatenated with String2", $string1);
Write-Host $string2;

There’s more than one way to skin a cat, at least so I am told, I’ve never skinned a cat in real life.  I don’t know when I figured out that you can do direct placement of variables inside of strings and save key strokes, but a lot of my Powershell code is written with the variables inline to the text that they are being concatenated into like the subject line in the blog post mentioned above.

Published Friday, June 18, 2010 4:36 PM by Jonathan Kehayias
Filed under:



Laerte Junior said:

Great. This is the difference of working with double and single quotes in Powershell. When we use the quotes the variable is changed by its value and when we use the single quote  that does not happen. So as Dan Jones explains, when we do not need this feature , a good practice is to use single quotes to avoid the unnecessary use of resources.

June 18, 2010 4:05 PM

Ronald Dameron said:

The variable expansion works because the statement is wrapped by double quotes.

If it were wrapped in single quotes it would not.

The use of quotes is explained in Windows PowerShell in Action by Bruce Payette. I think Lee Holmes explains it in his Windows PowerShell Cookbook too.

June 18, 2010 4:20 PM

Rob Farley said:

...and if you wanted to actually put the name of the variable in the string, you use single quotes instead (which is very useful when trying to start services of named instances)

June 18, 2010 6:07 PM
Anonymous comments are disabled

This Blog


Privacy Statement