Dec 212010
 

Often times you want to use an object’s specific property to let the user know what’s going on. The problem is that PowerShell won’t allow its dot notation within quotes. When you first try it you might be confused by the results.

$Files = Get-ChildItem
"This directory has $Files.Count files"

>> This directory has Contacts Desktop Documents.Count files

The reason is that PowerShell is only looking for a variable name and ignoring anything else. In this case it is converting all the items held in the $Files variable and displaying it as a string. That makes you tempted to create a variable whose only purpose is to be used in a string on the following line.

$Files = Get-ChildItem
$NumberFiles = $Files.Count
"This directory has $NumberFiles files"

>> This directory has 3 files

This will certainly get you by, but it adds lines of code and variables that won’t be used for anything else. Instead, you can make PowerShell think that you have created a variable simply by surrounding the variable and its dot notation in $() which basically creates a temporary variable which you can work with as you please.

$Files = Get-ChildItem
"This directory has $($Files.Count) files"

>> This directory has 3 files

In this manner you eliminate a useless variable and an excess line of code, but it doesn’t have to stop there. You can even place code blocks inside and really shorten things up. To make our sample code a single line I will use two sets of $(). One to make a temporary variable for Get-ChildItem and one to read the property “Count” and send the output to the string.

"This directory has $($(Get-ChildItem).count) files"

>> This directory has 3 files

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">