Can I specify a dll from which to use New-Object in Powershell?

大憨熊 提交于 2021-02-10 04:19:30

问题


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.


回答1:


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()



回答2:


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.



来源:https://stackoverflow.com/questions/48010715/can-i-specify-a-dll-from-which-to-use-new-object-in-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!