gpt4 book ai didi

.net - PowerShell - 检查 .NET 类是否存在

转载 作者:行者123 更新时间:2023-12-02 22:34:19 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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 - PowerShell - 检查 .NET 类是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43647107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com