Converting Objects Into Text

by Jul 27, 2009

PowerShell internally always works with objects, and this can cause confusion when you mix object and string technologies.

In a previous example, you learned how to retrieve all font families like this:

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
$families = (New-Object System.Drawing.Text.InstalledFontCollection).Families

If you tried to filter out only font families that match "Wingdings", you might have tried Select-Object like this:

$families | Select-String "Wingdings"

The result isn't what you expected , though. As it turns out, $families does not contain a collection of plain text strings but objects instead:

$families[0].GetType().FullName
System.Drawing.FontFamily

You would first have to explicitly convert the objects into plain text strings to then process them with Select-String. There is a way to do that: pipe objects through Out-String -stream, and they become text:

$families | Select-String "Wingdings"

You could also take a closer look at the objects and then determine yourself which property you would like to pass on in the pipeline.

$families[0] | gm -memberType *property

As it turns out, FontFamily objects only have one property called Name which is a string. So you could have also used this line:

$families | ForEach-Object { $_.Name } | Select-String "WingDings"

Now, it may occur to you that you could search for specific font families in yet another way:

$families | Where-Object { $_.Name -like '*WingDings*' } |
ForEach-Object { $_.Name }