ps/Modules/Cole.PowerShell.Developer/Public/Find-AssembliesThatReferenceByFragment.ps1

79 lines
3.0 KiB
PowerShell
Raw Normal View History

2023-05-30 22:51:22 -07:00
function Find-AssembliesThatReferenceByFragment {
<#
.SYNOPSIS
Occasionally with ORB it is helpful to find all the assemblies under a given folder that reference a specific fragment.
.PARAMETER ClassNameFragment
This is a partial fragment or full class name.
The actual comparison looks like this: C# > .GetReferencedAssemblies().Where(x => x.Name.StartsWith(exportedTypeName, StringComparison.InvariantCultureIgnoreCase))
.PARAMETER Folder
Where to look for the DLLs. Will recurse this folder and all subdirectories.
#>
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Alias('Name')]
[string]$ClassNameFragment,
[Parameter(Mandatory = $false)]
[Alias('Path')]
[string]$Folder = (Get-OrbPath)
)
# The use of the job allows us to redefine the C# code as often as we need, in case we change it while it's loaded previously
# This is just a semi-best-practice, because it does mean frequent recompilation.
# On the other hand, this is used infrequently, so ...
Start-Job -ArgumentList @( $ClassNameFragment, $Folder) -ScriptBlock {
param(
$ClassNameFragment, $Folder
)
Add-Type -TypeDefinition @"
namespace Finder {
using System;
using System.IO;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
public static class Finder {
public static IList<string> FindIt(string exportedTypeName, string targetFolder) {
var returnLines = new List<string>();
var assIgnoreList = new List<string>{"mscorlib"};
var di = new DirectoryInfo(targetFolder);
var fileList = di.GetFiles("*.dll", SearchOption.AllDirectories).Select(x => x.FullName).ToList();
foreach(var file in fileList) {
try {
Assembly.LoadFrom(file);
} catch {
assIgnoreList.Add(file);
}
}
foreach(var ass1 in AppDomain.CurrentDomain.GetAssemblies()) {
var refs = ass1.GetReferencedAssemblies().Where(x => x.Name.StartsWith(exportedTypeName, StringComparison.InvariantCultureIgnoreCase));
if (refs.Any()) {
foreach (var ref1 in refs) {
if (returnLines.Any()) {
returnLines.Add(string.Empty);
}
//returnLines.Add(string.Format("{2} :: {0} Loads --> {1}", ass1.FullName, ref1.FullName, ass1.Location));
returnLines.Add(ass1.Location);
returnLines.Add(string.Format(" {0}", ass1.FullName));
returnLines.Add(string.Format(" Loads -> {0}", ref1.FullName));
}
}
}
return returnLines;
}
}
}
"@
$exportedTypeName = $ClassNameFragment
$startingFolder = $Folder
[Finder.Finder]::FindIt($exportedTypeName, $startingFolder) # | Out-String
} | Receive-Job -Wait -AutoRemoveJob
}