繁体   English   中英

PowerShell - 检查 .NET 类是否存在

[英]PowerShell - Check if .NET class exists

我有一个要导入 PS 会话的 DLL 文件。 这将创建一个新的 .NET 类。 在函数开始时,我想测试这个类是否存在,以及它是否不导入 DLL 文件。

目前我正在尝试给班级打电话。 这有效,但我认为它会导致 Do {} 直到 () 循环出现问题,因为我必须运行脚本两次。

我的代码。 请注意Do {} Until ()循环不起作用。 https://gist.github.com/TheRealNoob/f07e0d981a3e079db13d16fe00116a9a

我找到了[System.Type]::GetType()方法,但是当我针对任何类型的字符串、有效或无效的类运行它时,它不会做任何事情。

您可以在 powershell 中使用-as将字符串转换为[system.type]

PS C:\> 'int' -as [type]

IsPublic IsSerial Name    BaseType
-------- -------- ----    --------
True     True     Int32   System.ValueType

如果找不到类型(与其他强制转换场景一样),则表达式不会返回任何内容:

PS C:\> 'notatype' -as [type]

PS C:\> 

因此,您可以使用以下命令检索特定类型(无需遍历应用程序域中加载的所有程序集的所有类型):

$type = 'notatype' -as [type]

#or

if ('int' -as [type]) { 
  'Success!' 
}

#and conveniently

$typeName = 'Microsoft.Data.Sqlite.SqliteConnection'
if (-not($typeName -as [type])) {
   #load the type
}

在 .Net 中,它存在一种叫做 Reflexion 的东西,它允许您处理代码中的所有内容。

$type = [System.AppDomain]::CurrentDomain.GetAssemblies() | % { $_.GetTypes() | where {$_.Name -eq 'String'}}

在这里,我查找类型String ,但您可以查找您的类型或更好的程序集版本,您甚至可以查找是否存在具有正确参数的方法。 看看C# - 如何检查 C# 中是否存在命名空间、类或方法? .


@Timmerman 评论; 他和:

[System.AppDomain]::CurrentDomain.GetAssemblies() | % { $_.GetTypes() | where {$_.Name -like "SQLiteConnection"}}

或者

[System.AppDomain]::CurrentDomain.GetAssemblies() | % { $_.GetTypes() | where {$_.AssemblyQualifiedName -like 'Assembly Qualified Name'}}

这就是 -is 和 -as 的用途。 您还可以使用带有 try/catch 语句的 -is 来检查该类是否存在:

try
{
   [test.namespace] -is [type]
}
catch
{
    add-type -typedefinition test.namespace.dll
}

el2iot2 完美地描述了 -as 的使用,这将是我的首选方法。 它旨在不通过类转换期间的错误。

我推荐使用-as的 el2iot2 方法

如果您比-as更喜欢 try-catch 方式,我建议您将我的答案中的[SomeType]::Equals($null, $null)替换为[SomeType] -is [type] ,根据Shaun Stevens 的回答

但是,如果我既没有阅读 el2iot2 也没有阅读 Shaun Stevens 的回答,我会使用以下内容:

try {
    [SomeType]::Equals($null, $null) >$null
    Write-Host '"SomeType" exists'
}
catch {
    Write-Host '"SomeType" does not exist'
}

(解释:每个类型都应该有Equals静态方法,它允许用两个$null调用自己并在这种情况下返回$true ;尝试以这种方式引用一个不存在的类型应该抛出一个SystemException的实例,它可以被抓住。)

它甚至可以用作单线:

$someTypeExists = try {[SomeType]::Equals($null, $null)} catch {$false}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM