PowerShell - 检查 .NET 类是否存在 [英] PowerShell - Check if .NET class exists

查看:43
本文介绍了PowerShell - 检查 .NET 类是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

<小时>

@Timmerman 评论;他去了:

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

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

I have a DLL file that I am importing into the PS session. This creates a new .NET class. At the start of the function I want to test if this class exists, and if it doesn't import the DLL file.

Currently I am trying to call the class. This works but I think it's causing problems with the Do {} Until () loop since I have to run the script twice.

my code. note the Do {} Until () loop isn't working. https://gist.github.com/TheRealNoob/f07e0d981a3e079db13d16fe00116a9a

I have found the [System.Type]::GetType() Method but when I run it against any kind of string, valid or invalid class, it doesn't do anything.

解决方案

In .Net it exists something called Reflexion which allow you deal with everything in your code.

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

Here I look for the type String, but you can look for your type or better the version of the Assembly, you can even find if one method exists with the correct arguments. Have a look to C# - How to check if namespace, class or method exists in C#?.


@Timmerman comments ; he went with :

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

or

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

这篇关于PowerShell - 检查 .NET 类是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆