PowerShell Tip: Searching for Controls Without a Fully-qualified Type Name

May 28 2010 One comment

Today’s post is a quick tip. I’m working with some older code where a lot of the ascx files don’t have a fully qualified type name in the Inherits attribute of the Control directive. I wanted to find them without having to open dozens of files and manually search for offenders:

function Find-Controls-Without-PublicKeyToken([string]$directory) {
    $files = dir $directory -Recurse -Filter *.ascx
    $files | where { No-Publickeytoken($_) } | foreach { $_.FullName }

This is a pretty straightforward function, it finds all the user control files in a given directory or any of its subdirectories, filters the list using No-Publickeytoken and prints out the paths to the offending files. And here’s No-Publickeytoken:

function No-Publickeytoken($file) {
    $firstLine = Get-Content $_.FullName -TotalCount 1
    ($firstLine -match "Inherits") -and `
        (-not ($firstLine -match "PublicKeyToken"))

This function gets the first line of the file passed to it and then returns true if the line contains the word “Inherits” but doesn’t contain the word “PublicKeyToken”.

Hope this is useful to someone, it certainly saved me a bunch of repetitive manual work. :-)

Popularity: 1% [?]

One comment to “PowerShell Tip: Searching for Controls Without a Fully-qualified Type Name”

  1. Jouni says:

    A minor nit: “No-PublicKeyToken” is named in conflict with PowerShell best practices. For boolean returning test predicate functions/cmdlets, “Test” is the standard verb. Therefore, “Test-HasNoPublicKeyToken” might be a good name for the function.

    Certainly useful code though :-)

Leave a Reply