Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  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 log on before posting a comment.

If you don't have a username & password, please 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
WinInfo Short Takes: Week of September 8, 2008

An often irreverent look at some of the week's other news, including the long-awaited back to school season, Microsoft's first Seinfeld/Gates ad, some EU insights, another Netbook improvement, Opera silliness, and much, much more ...

Friday at PASS Europe 2006

Kevin talks about the closing day of the event and shares a funny Microsoft film. ...

IE 8.0 and Chrome Could Enable Next-Gen Web Apps—Unless Your ISP's Bandwidth Cap Gets in the Way

Both browsers are being positioned as the core system application that will enable the next generation of web apps--however, ISP usage caps could throw a major monkey wrench at web-based application delivery. ...


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

Windows OSs Whitepapers Why SaaS is the Right Solution for Log Management

Are You Satisfied?

A Preliminary Look at Deployment Plans for Microsoft Windows Vista

Related Events 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 Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.

Job Openings in IT


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

IT Connections
Dive into the new Microsoft platforms and products you implement and support with the experts from Microsoft, TechNet Magazine, Windows ITPro and industry gurus. There are 70+ sessions and interactive panels with networking opportunities.

Attention User Group Leaders...
Announcing the eNews Generator—a FREE HTML e-newsletter builder for user group leaders. Build your HTML and text e-newsletters in minutes and add Windows IT Pro & SQL Server Mag articles alongside your own message!.

Master SharePoint with 3 eLearning Seminars
Learn how to build a better SharePoint infrastructure and enable powerful collaboration with MVPs Dan Holme and Michael Noel. Register today!

Get SQL Server 2008 at WinConnections
Don’t miss Microsoft Exchange and Windows Connections conferences, the premier events for Microsoft IT Professionals in Las Vegas, November 10-13. Every attendee will receive a copy of SQL Server 2008 Standard Edition with one CAL.



Interested in Email Encryption?
Read about the advantages of identity-based encryption in this free report.

Order Your SQL Fundamentals CD Today!
Learn how to use SQL Server, understand Office integration techniques and dive into the essentials of SQL Express and Visual Basic with this free SQL Fundamentals CD.

Virtualization Congress Oct. 14-16 in London
Don't miss Virtualization Congress, the premiere EMEA conference dedicated to hardware, OS and application virtualization. Oct. 14-16.
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 Windows Dev Pro IT Job Hound ITTV
IT Library Technical Resources Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing