Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


May 2008

PowerShell 101, Lesson 4

How to properly use quotes when working with strings
RSS
Subscribe to Windows IT Pro | See More Systems Administration Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!
SideBar    Getting and Using the System.String Object's Members

This statement uses the GetType method of the object’s type, which in this case is String, or more specifically System.String, also shown in Figure 2. For more information about System.String and GetType, see the sidebar “Getting and Using the System.String Object’s Members.”

If you don’t enclose a numerical value in quotes, PowerShell treats the value as a numerical object. For example, the following statement returns an integer object:

Write-Output 123

Again, you can verify the object’s type by using the GetType method:

(Write-Output 123).GetType()

As you can see in Figure 2, the object’s type is Int32.

If a value includes both numbers and letters, PowerShell treats it as a string, whether or not it’s in quotes. For example, the following statement returns a string, as verified by the second statement:

Write-Output 123output
(Write-Output 123output).GetType()

Once again, Figure 2 shows the output of these statements.

In most cases, you can omit quotes if your argument is a string with no embedded spaces. For example, the following three statements use the Set-Location cmdlet to set the working folder to the C drive:

Set-Location C:\  
Set-Location “C:\”
Set-Location ‘C:\’
Now suppose you want to change the working folder to C:\Documents and Settings:
Set-Location `
  C:\Documents and Settings

This statement generates an error because it doesn’t know what to do with the tokens (words) after the first space. As you can see in Figure 3, the parser interprets “and” as a parameter, and because there’s no parameter by this name, the parser generates an error. You can easily fix this problem by enclosing the entire argument in quotes:

Set-Location `
  “C:\Documents and Settings”

Now when you run this statement, it changes the working folder, as shown in Figure 3.

One other important issue when working with strings is how to reference variables within a quoted string. If you enclose a string in double quotes, the variable’s value is used. If you enclose a string in single quotes, the literal value is used. As I mentioned earlier, I’ll cover variables and describe how to reference them in strings in the next lesson. However, if you’re anxious to learn more about using variables in your strings now, refer to the about_quoting_ rules Help file.

Escaping Special Characters in Strings
Up to this point, the arguments you’ve seen in the examples could have taken single or double quotes. As a result, it would appear that there’s no difference between the two. However, there’s one very important difference: Single quotes always treat a string literally, whereas double quotes allow you to escape special characters within the text. A special character is one that, when preceded by a backtick (`), takes a specific action that it would not have taken without the backtick. Table 1 lists PowerShell’s special characters.

The best way to explain this concept is through a few examples. In the following statement, several characters have been escaped in order to change how the text is displayed:

Write-Output (“`n`tText includes” + `
  “`n`t`”escaped`” characters.`n”)

The first escaped character (the one preceded by the first backtick) is n, which in this context inserts a new line. The next escaped character is t, which inserts a tab. Note that the backtick at the end of the first line isn’t being used as an escape character but rather as a continuation character (see Lesson 2). In the second line, `n and `t are used several more times. In addition, backticks precede the double quotes surrounding the word escaped. As a result, the double quotes appear in the output. If you refer to Figure 4, you’ll see how the new lines, tabs, and double quotes appear. For more information about escaping characters, see the about_escape_character Help file.

If you try to escape characters in a string enclosed in single quotes, the backtick and special characters have no effect on the output, other than to be treated literally. For example, the statement

Write-Output ‘`tindented`n`twords’

returns the exact string as originally typed, as Figure 4 shows. Note that, in pre-release versions of PowerShell, you could escape characters inside single-quoted strings, and PowerShell would correctly parse them. So, you might come across material that says that this is how PowerShell handles singlequoted strings.

Moving Forward
In most cases, string values play an important role in creating PowerShell statements. The better you understand how to work with strings, the more effective your statements will be. I encourage you to spend time practicing the various ways to use strings. Try enclosing them in single and double quotes, then try running the commands without the quotes. And don’t forget to practice escaping special characters.

End of Article

   Previous  1  [2]  Next  


Reader Comments
This was useful

petmwintel May 27, 2008 (Article Rating: )


You must be a registered user or online subscriber to comment on this article. Please log on before posting a comment. Are you a new visitor? Register now




Learning Path To read the previous PowerShell 101 lessons, go to
"PowerShell 101, Lesson 1"

"PowerShell 101, Lesson 2"

"PowerShell 101, Lesson 3"


If you're beyond the basics, check out
"Enhance PowerShell's Syntax Display"

"Working with Shortcuts in Windows PowerShell"


Top Viewed ArticlesView all articles
2009 Windows IT Pro Editors' Best and Community Choice Awards

Picking a favorite product from an impressive crowd of competitive offerings is never an easy task, and such was the case with our Editors' Best and Community Choice awards this year. ...

Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

WinInfo Short Takes: Week of November 23, 2009

An often irreverent look at some of the week's other news, including some post-PDC some soul searching, a Google Chrome OS announcement and a Microsoft response, Windows 7 off to a supposedly strong start, the Jonas Brothers and Xbox 360, and so much more ...


Related Articles PowerShell Queries for Failed Services on Remote Machines

Making PowerShell's Out-Printer Cmdlet Easier to Use

Essential Windows PowerShell Commands

Dig Out by Digging Into PowerShell

Scripting Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Related Events Deep Dive into Windows Server 2008 R2 presented by John Savill

PowerShell 201 - eLearning Series with Paul Robichaux

PowerShell 101 - eLearning Series

Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement