Mic*_*man 8 .net powershell types
我有一个 DLL 文件,正在导入到 PS 会话中。这将创建一个新的 .NET 类。在函数开始时,我想测试这个类是否存在,以及它是否不导入 DLL 文件。
目前我正在尝试给班级打电话。这可行,但我认为它会导致 Do {} Until () 循环出现问题,因为我必须运行脚本两次。
我的代码。请注意Do {} Until ()循环不起作用。
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.
el2*_*ot2 10
[system.type]您可以使用以下命令将字符串转换为powershell 中的-asa:
PS C:\> 'int' -as [type]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
Run Code Online (Sandbox Code Playgroud)
如果找不到类型(与其他强制转换场景一样),则表达式不会返回任何内容:
PS C:\> 'notatype' -as [type]
PS C:\>
Run Code Online (Sandbox Code Playgroud)
因此,您可以使用以下命令检索特定类型(无需迭代应用程序域中加载的所有程序集的所有类型):
$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
}
Run Code Online (Sandbox Code Playgroud)
在.Net 中,存在一种称为反射的东西,它允许您处理代码中的所有内容。
$type = [System.AppDomain]::CurrentDomain.GetAssemblies() | % { $_.GetTypes() | where {$_.Name -eq 'String'}}
Run Code Online (Sandbox Code Playgroud)
在这里,我查找 type String,但您可以查找您的类型或更好的程序集版本,您甚至可以查找是否存在具有正确参数的方法。看看C# - 如何检查 C# 中是否存在命名空间、类或方法?。
@蒂默曼评论;他和:
[System.AppDomain]::CurrentDomain.GetAssemblies() | % { $_.GetTypes() | where {$_.Name -like "SQLiteConnection"}}
Run Code Online (Sandbox Code Playgroud)
或者
[System.AppDomain]::CurrentDomain.GetAssemblies() | % { $_.GetTypes() | where {$_.AssemblyQualifiedName -like 'Assembly Qualified Name'}}
Run Code Online (Sandbox Code Playgroud)