I’m trying to determine if a type is already loaded in PowerShell. Example code below:
try {
$httpHandler = New-Object -TypeName System.Net.Http.HttpClientHandler
} catch {
Write-Output -InputObject "Loading type.."
Add-Type -AssemblyName "System.Net.Http"
} # This works OK, but not ideal
# Example 1 -- check if the type is loaded
$types = Get-TypeData
if ($types | Where-Object {$_.TypeName -eq "System.Net.Http"}) {
Write-Output -InputObject "Loaded"
} else {
Write-Output -InputObject "Not loaded"
}
# The above returns 'Not loaded' in all cases
# Example 2 -- check if the type is loaded
[Type]::GetType("System.Net.Http", $false)
# Returns no output
Is there a way to check if a type is loaded/imported before calling Add-Type? There is no Get-Type Cmdlet that I can find
>Solution :
You can search for loaded types like this:
[AppDomain]::CurrentDomain.GetAssemblies() |
ForEach-Object {$_.GetTypes()} |
Where-Object Name -eq 'FileInfo'
Which gives output like this:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True FileInfo System.IO.FileSystemInfo