【发布时间】:2009-04-02 16:16:39
【问题描述】:
我有一组 .NET 程序集(都在同一个目录下),其中一些包含实现抽象类的类。我想要一个 Powershell 脚本来查找所有实现我的抽象类的类,并在每个类上执行一个方法。
有人知道怎么做吗?
谢谢!
【问题讨论】:
标签: reflection powershell assemblies
我有一组 .NET 程序集(都在同一个目录下),其中一些包含实现抽象类的类。我想要一个 Powershell 脚本来查找所有实现我的抽象类的类,并在每个类上执行一个方法。
有人知道怎么做吗?
谢谢!
【问题讨论】:
标签: reflection powershell assemblies
这是您可能想尝试的一个小功能..(我还没有测试它,因为我没有任何标准可以轻松测试它..)
可以像这样在命令行中提供路径(一个或多个完整路径或以逗号分隔的相对路径)来使用它
CheckForAbstractClassInheritance -Abstract System.Object -Assembly c:\assemblies\assemblytotest.dll, assemblytotest2.dll
或来自管道
'c:\assemblies\assemblytotest.dll','assemblytotest2.dll' | CheckForAbstractClassInheritance -Abstract System.Object
或使用 Get-Childitem (dir) 中的 fileinfo 对象
dir c:\assemblies *.dll | CheckForAbstractClassInheritance -Abstract System.Object
根据需要进行调整..
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
}
}
}
}
}
【讨论】:
与使用 c# 的方法相同,但使用 PowerShell 语法。
看看Assembly.GetTypes 和Type.IsSubclassOf。
【讨论】: