Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validate if a type is loaded in PowerShell

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading