Powershell Reflection

I have a .NET Assemblies collection (all under the same directory), and some of them contain classes that implement the abstract class. I would like the Powershell script to detect all classes that implement my abstract class and execute a method for each of them.

Does anyone have an idea on how to do this?

Thanks!

+4
source share
2 answers

Here is a small feature that you might want to try. (I have not tested it yet, as I have no criteria to test this with ease.)

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

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

or from the conveyor

 '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 

Underline as necessary ..

 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 } } } } } 
+3
source

Just like you do with C #, but with PowerShell syntax.
Take a look at Assembly.GetTypes and Type.IsSubclassOf .

0
source

All Articles