Finding PowerShell Classes

Starting in PowerShell 5, you can define PowerShell classes. They are defined dynamically and live in memory. So how would you know the names of classes that have been defined?

Let’s first define a really simple class that does not do anything:

class TestClass
{
    
}

How would you be able to check whether a class named “TestClass” exists in memory? Here is a helper function called Get-PSClass:

function Get-PSClass($Name = '*')
{
  [AppDomain]::CurrentDomain.GetAssemblies() | 
  Where-Object { $_.GetCustomAttributes($false) | 
      Where-Object { $_ -is [System.Management.Automation.DynamicClassImplementationAssemblyAttribute]} } | 
      ForEach-Object { $_.GetTypes() | 
      Where-Object IsPublic |
      Where-Object { $_.Name -like $Name } |
      Select-Object -ExpandProperty Name
  }
}

When you run it, it reports the names of all currently defined PowerShell classes in memory (in our PowerShell example, there were a couple of other PowerShell classes found from previous experiments as well):

 
PS> Get-PSClass
HelperStuff
Employee
TestClass

PS>  
 

You can also explicitly test for a class name:

 
PS> Get-PSClass -Name TestClass
TestClass

PS> (Get-PSClass -Name TestClass) -ne $null 
True

PS> (Get-PSClass -Name TestClassNotExisting) -ne $null 
False
 

And you can use wildcards. This would report any class starting with an “A” through “H”:

 
PS> Get-PSClass -Name '[A-H]*'
HelperStuff
Employee
 

Twitter This Tip! ReTweet this Tip!