5

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!

2 Answers 2

3

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
                }
            }

        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The only issue here is that you cannot instantiate classes or execute methods from assemblies that have been loaded for reflection only.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.