header image

W2KSG: Concatenating Strings

Posted by: | August 26, 2008 | No Comment |

We have seen how to use a string as a variable.  How do we join, or concatenate two strings.  The scripting guide has an example 

Script Center Home > Microsoft Windows 2000 Scripting Guide > Scripting Concepts and Technologies for System Administration > VBScript Primer > VBScript Overview > Strings Concatenating Strings

## listing 2.7

$convert = 1MB
$computer = "pcrs2"

Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk -Filter "DeviceId=’C:’" | ForEach-Object {

"There are " + [int]($_.Freespace/$convert) + " megabytes of free disk space"
"There are $([int]($_.Freespace/$convert)) megabytes of free disk space"

We determine the free space as before.  This time we need to use a foreach-object to loop through the returned data.  We have only selected a single drive but it is still returned as a collection of objects rather than a single object.

If a string is defined on a line it is automatically written out. In the first example the strings are concatenated using the + symbol.  [int]($_.Freespace/$convert) is automatically turned into a string as integer to string is an allowed conversion.

In the second example we make use of PowerShell’s ability to substitute values into a double quoted string. $([int]($_.Freespace/$convert))  tells PowerShell to treat everything between the outer() as a variable that will be substituted into the string.

Two ways of achieving the goal of embedding the value into the string. Use which ever you most comfortable with though the later is the more powerful.


Share this post :


Technorati Tags: PowerShell

under: PowerShell original