Ryan Witschger

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
Dec 212010
 

Sometimes your PowerShell code can start to fly off the right side of the screen, especially when you are using commands like write-progress. To space your code down, make it more tidy, and get it to fit on one screen just use the (backtick) key. That’s the ~ (Tilde) key without the shift!

Write-Progress -Activity "Testing New Lines" <code>
-Status "Still Testing" </code>
-CurrentOperation "Testing File $Filename" <code>
-PercentComplete ($Something / $SomethingElse * 100) </code>
-SecondsRemaining $Timer.TotalSeconds