3

I have a scenario where by I need to New-Object a type but there are multiple types with the same name and namespace. I can't find how New-Object decides which dll to create the type from when it exists in multiple places. Is it possible to specify? Ideally I'd like to pass the dll name to the New-Object but there doesn't appear to be an option for this.

Sio
  • 1,269
  • 1
  • 11
  • 19

2 Answers2

6

Specify the full assembly-qualified type name:

New-Object -TypeName 'MyType, AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=abcdef0123456789'

This works with type literals as well:

[MyType,AssemblyName,Version=1.0.0.0,Culture=neutral,PublicKeyToken=abcdef0123456789]::new()

You can easily obtain the fully qualified name of an assembly from disk with AssemblyName.GetAssemblyName():

# Load the assembly
$AssemblyPath = '.\MyAssembly.dll'
Add-Type -Path $AssemblyPath

# Fetch the assembly's name
$AssemblyName = [System.Reflection.AssemblyName]::GetAssemblyName((Resolve-Path $AssemblyPath).Path)

# Construct full type name
$TypeName = 'MyType'
$AssemblyQualifiedTypeName = $TypeName,$AssemblyName -join ', '

# Instantiate and object of this type
$MyObject = New-Object -TypeName $TypeName
#or
$MyObject = ($TypeName -as [Type])::new()
Mathias R. Jessen
  • 106,010
  • 8
  • 112
  • 163
  • You can get the assembly's qualified type name (aka, assembly strong name, or assembly full name) directly with `[System.Reflection.AssemblyName]::GetAssemblyName($Path).FullName`. If the type is already loaded, you can call `([TypeName]).Assembly` to get the assembly or `([TypeName]).Assembly.FullName` or `[System.Reflection.Assembly]::GetAssembly([TypeName]).FullName` to get the qualified type name from the type. – Bacon Bits Dec 29 '17 at 07:22
1

I think you can try to use LoadFrom:

[System.Reflection.Assembly]::LoadFrom(dllPath)

Then PS should first look into it when using New-Object FullyQualifiedType .

EDIT :

Alternatively, it seems there is an option to specify an DLL assembly with Add-Type :

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/add-type?view=powershell-5.1

Add-Type -AssemblyName "yourAssembly" 

Then, the type will be available in the current PowerShell session.

Pac0
  • 16,761
  • 4
  • 49
  • 67