我有一个场景,我需要New-Object
一个类型,但有多个具有相同名称和命名空间的类型。我找不到如何New-Object
当类型存在于多个位置时,决定从哪个 dll 创建该类型。可以具体说明一下吗?理想情况下,我想将 dll 名称传递给New-Object
但似乎没有这样的选择。
指定完整的程序集限定类型名称:
New-Object -TypeName 'MyType, AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=abcdef0123456789'
这也适用于类型文字:
[MyType,AssemblyName,Version=1.0.0.0,Culture=neutral,PublicKeyToken=abcdef0123456789]::new()
您可以轻松地从磁盘获取程序集的完全限定名称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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)