PowerShell: How to Convert Object Property to String


Often you may want to convert an object property to a string in PowerShell.

You can use the following methods to do so:

Method 1: Convert Property to Array of Strings

$my_string = Dir | Select -Expand Name

This particular example converts the property named Name into an array of strings named $my_string.

Method 2: Convert Property to Single String with Comma-Separated Values

$my_string = (Dir | Select -expand Name) -join ","

This particular example converts the property named Name into a single string named $my_string that contains each value from the property, separated by commas.

Note that both methods use the -expand parameter to convert a specific property into a string.

The following example shows how to use each of these methods in practice.

Example 1: Convert Property to Array of Strings

Suppose we use the following syntax to extract each of the folders in the current directory:

Dir | Select Name

The following screenshot shows how to use this syntax in practice:

This returns an object that contains one property with the name of Name.

Suppose that we would like to convert this property into an array of strings.

We can use the following syntax to do so:

$my_string = Dir | Select -Expand Name

The following screenshot shows how to use this syntax in practice:

Notice that $my_string is an array that contains each of the values from the property named Name.

When we use $my_string[0], we are able to extract the first value from the property.

We can use similar bracket notation to extract each value from the property.

Example 2: Convert Property to Single String of Comma-Separated Values

We can use the following syntax to convert a property named Name into a single string in which the values from the property are separated by commas:

$my_string = (Dir | Select -expand Name) -join ","

The following screenshot shows how to use this syntax in practice:

PowerShell convert object property to string of comma-separated values

Notice that $my_string is a single string that contains each of the values from the property named Name, separated by commas.

Note: In this example we used the -join operator to concatenate all values from the property using a comma, but you can use any separator you’d like.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List All Object Properties
PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply