Tuesday, April 7, 2020

PowerShell: Use Single Quotes Where Possible

As a general rule, PowerShell scripts should use strings marked by single quotes rather than double quotes. Using single quotes tells anyone reading the code, "This string will not contain variable substitution." Strings demarcated by double quotes support variable substitution.

In a previous posting, I declared a variable $key1 and deliberately used single quotes:

[string] $key1 =
            'HKLM:\SOFTWARE\Microsoft\Windows\' +
            'CurrentVersion\App Paths\chrome.exe'

The message to any developing reading the above code is that there would be parameters injected into the string because of the single quotes. I have seen example after example online of PowerShell where double quotes are used and there are no variable specified for substitution:

[string] $key2 =
            "HKLM:\SOFTWARE\Microsoft\Windows\" +
            "CurrentVersion\App Paths\chrome.exe"

Exception to the Rule: Variable Substitution

A double quoted string should be used when a variable to be replaced is specified. The previous string is technically correct but it contains no variable inside the double quotes so there is no point in using double quotes over single quotes. A string such as the following (variable $key3) takes advantage of variable substitution and is therefor surrounded by double quotes:

[string] $chromeExecutable = 'chrome.exe'
[string] $key3 =
            'HKLM:\SOFTWARE\Microsoft\Windows\' +
            "CurrentVersion\App Paths\$chromeExecutable"

The variable $key1 and $key3 will both have the same value where $key3 is assigned this value by substituting the parameter $chromeExecutable.

Exception to the Rule: Escape Sequences

The blog entry "PowerhShell: Escape Sequences (NewLine, Tab, BackSpace, etc)" demonstrated escape sequences. Consider a scenario where PowerShell and Selenium are being used to automate a web page and the term 'Wedding Present' is being searched for. One way to trigger the search button would be to invoke the Enter key. The text to pass to the Selenium API invoke the search button would be "Wedding Present`n" which requires double quotes so that the text 'Wedding Present' is passed including the escape sequence for the Enter key, `n.

Exception to the Rule: SQL Queries

There are other times when a double quoted string is useful in PowerShell. T-SQL uses single quotes for strings so a double quoted string PowerShell can contain single quotes. An example of T-SQL where single quotes are used inside a double quoted PowerShell string is as follows:

"SELECT * FROM Employee WHERE LastName LIKE 'S%' ORDER BY LastName"

The previous T-SQL select will select all employees where the last name starts with the letter S (WHERE LastName LIKE 'S%') and nested within the query are the single quotes used for the look up starts with the letter S, 'S%'.

No comments :

Post a Comment