views:

333

answers:

2

I have a set of .NET Assemblies (all under the same directory) and some of those contain classes which implement an abstract class. I would like a Powershell script to find all the classes which implement my abstract class, and execute a method on each of them.

Does anybody have an idea on how to do this?

Thanks!

A: 

The same way as you do it with c# but with PowerShell syntax.
Take a look at Assembly.GetTypes and Type.IsSubclassOf.

Shay Erlichmen
+1  A: 

Here's a little function you might want to try.. (I haven't tested it yet, as I don't have any criteria to test this with easily..)

It can be used by supplying the paths (one or more full or relative paths separated by commas) on the command line like this

CheckForAbstractClassInheritance -Abstract System.Object -Assembly c:\assemblies\assemblytotest.dll, assemblytotest2.dll

or from the pipeline

'c:\assemblies\assemblytotest.dll','assemblytotest2.dll' | CheckForAbstractClassInheritance -Abstract System.Object

or with fileinfo objects from Get-Childitem (dir)

dir c:\assemblies *.dll | CheckForAbstractClassInheritance -Abstract System.Object

Tweak as needed..

function CheckForAbstractClassInheritance()
{
    param ([string]$AbstractClassName, [string[]]$AssemblyPath = $null)
    BEGIN
    {
        if ($AssemblyPath -ne $null)
        {
            $AssemblyPath | Load-AssemblyForReflection
        }
    }
    PROCESS
    {
        if ($_ -ne $null)
        {
            if ($_ -is [FileInfo])
            {
                $path = $_.fullname
            }
            else
            {
                $path = (resolve-path $_).path
            }
            $types = ([system.reflection.assembly]::ReflectionOnlyLoadFrom($path)).GetTypes()
            foreach ($type in $types)
            {
                if ($type.IsSubClassOf($AbstractClassName))
                {
                    #If the type is a subclass of the requested type, 
                    #write it to the pipeline
                    $type
                }
            }

        }
    }
}
Steven Murawski