The task in Beginner’s Event 2 was to list out how a computer’s installed True Type fonts, and print a count of them (and of the total fonts). This really isn’t worth explaining, because it’s so simple, but again, the Scripting Guys Solution uses these extremely wordy mechanisms that make everything seem like so much work … I felt like I had to post a couple of alternate solutions. Lets start with the cleanest. Oh, and by the way, the code reads a lot better if you click through to the wider single-article layout of my site. ;-)


# get all the font names from the registry as required, but I'm lazy,
# so I use *s and let the computer figure the path out
$fonts = (get-item "HKLM:\Soft*\Microsoft\* NT\Cur*ion\Fonts").GetValueNames()

# But we only want the true type ones
$ttf = $fonts -match "TrueType"

# Now print everything out:
$ttf
""
"TrueType: " + $ttf.Count
"Total: " + $fonts.Count

Notice the total lack of the statement for or foreach? That’s a beautiful thing. My favorite part is the line $ttf = $fonts -match "TrueType". Filtered array assignment works with any comparison operators, it’s very nice. Please use it. And yes, if all you wanted was to print out the TrueType font names, this one-liner would suffice:


(get-item "HKLM:\Soft*\Microsoft\* NT\Cur*ion\Fonts").GetValueNames() -match "TrueType"

Ok, for those of you who just can’t stand not having counter variables … do yourself a favor, and at least learn the syntax for switch -regex:


$ttf=0; $fonts=0;           # you don't have to zero these out if they're already empty

switch -regex ((get-item "HKLM:\Soft*\Microsoft\* NT\Cur*ion\Fonts").GetValueNames()) {
  "TrueType" { $ttf++; $_ } # for true type fonts, increment the counter and print it out
  default {$fonts++}        # for everything else, just increment the counter
}
""
"TrueType: " + $ttf
"Total: " + $ttf + $fonts

Comments are closed.