wasif
wasif

Reputation: 15488

List the classes of a .NET namespace in powershell?

I am trying to list the classes of a .NET namespace.

Example, a namespace [System.IO]. I am trying to list its classes like [System.IO.Path], File, Directory, StreamReader etc.

Here when I directly type [System.IO] on the console I get an error that the type cannot be found. Get-Member doesn't help because it lists methods and properties of a class.

Does any one know how to do that?

Upvotes: 6

Views: 4694

Answers (3)

Maybe
Maybe

Reputation: 975

This is how I would do it, it filters out junk like System.IO.File+<<WriteAllBytesAsync>g__Core|92_0>d, just pipe in the namespaces you want at the start:

'System.IO' | Write-Output -pv ns | &{process{
  [AppDomain]::CurrentDomain.GetAssemblies().GetTypes().
  Where{ $_.Namespace -eq $ns }.FullName -notlike '*+<*'
}} | Sort-Object -Unique

Or turn it into a proper function:

function Get-NamespaceTypes {
  param(
    [Parameter(Position=0,ValueFromPipeline,Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string[]] $Namespace
  )
  begin {
    $sortedSet = [Collections.Generic.SortedSet[string]]::new()
  }
  process {
    try {
      $sortedSet.UnionWith(
       $(foreach( $p in $PSBoundParameters['Namespace'] ){
          [AppDomain]::CurrentDomain.GetAssemblies().GetTypes().Where{
            $_.Namespace -eq $p
          }.FullName.Where{
            -not $_.Contains('+<')
          }
        }) -as 'string[]'
      )
    }
    catch {
      $PSCmdlet.ThrowTerminatingError($_)
    }
  }
  end {
    return $sortedSet
  }
}

Upvotes: 0

Justin
Justin

Reputation: 1503

in powershell:

[AppDomain]::CurrentDomain.GetAssemblies().GetTypes()  | Where-Object {$_.NameSpace -eq 'System.IO'}

Upvotes: 8

Martin
Martin

Reputation: 16433

Following your comment 'C# is very related to .NET I will also accept C# solutions', I have a quick and dirty C# solution to list all the types in the System.IO namespace.

The below code can easily be adapted for any namespace but note that it only works on loaded assemblies in the current app domain:

List<Type> types;
types = new List<Type>();

foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
    types.AddRange(ass.GetTypes().Where(x => x.Namespace == "System.IO"));

// Do something with the list of types

Listing types from non-loaded assemblies is a lot trickier. You could enumerate all assemblies in the GAC or from specified folders, but finding every single type is nigh-on impossible given that any assembly (i.e. one I can make now) can add to System.IO.

Upvotes: 3

Related Questions