如何严格将变量键入为特定的WMI类? [英] How do I strictly-type a variable as a specific WMI class?
本文介绍了如何严格将变量键入为特定的WMI类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在大多数情况下,对功能参数的期望是 [wmiclass]
。但是,我正在使用带有自定义类的自定义名称空间。当我使用 Get-Member
时,它的显示类型为:
In most cases, what you're expecting for a function parameter is [wmiclass]
. However, I'm working in a custom namespace with a custom class. When I use Get-Member
, it shows the type as:
System.Management.ManagementClass#ROOT\namespace\class_name
如何将WMI类指定为变量类型?此示例不起作用:
How do I specify that WMI class as a variable type? This example doesn't work:
param(
[wmiclass#root\namespace\class_name]
$Class
)
此返回
Unable to find type [System.Management.ManagementClass#ROOT\namespace\class_name].
就这个问题而言,假设我我正在尝试定位
For the purpose of this question, let's say I'm trying to target
ROOT\cimv2\Win32_Service
标记 c#
,因为它与切向相关我很好奇这是否可以解决
tagging c#
since it's tangentially related and I'm curious if this is solved there
推荐答案
您能做到吗?
Param (
[PsTypeName("System.Management.ManagementClass#ROOT\namespace\class_name")]
$Class
)
或者如果使用CIM代替WMI,则:
Or if using CIM instead of WMI, this:
Param (
[PsTypeName("System.Management.Infrastructure.CimInstance#root/namespace/class_name")]
$Class
)
测试案例:
function test {
Param (
[psTypename("System.Management.ManagementClass#ROOT\cimv2\StdRegProv")]
$mine
)
$mine
}
$reg = [wmiclass]"\\.\root\cimv2:StdRegprov"
$reg | gm
#outputs: TypeName: System.Management.ManagementClass#ROOT\cimv2\StdRegProv
[wmiclass]$wmi = ""
$wmi | gm
# outputs: TypeName: System.Management.ManagementClass#\
test $wmi
# Errors: test : Cannot bind argument to parameter 'mine', because PSTypeNames of the argument do not match the PSTypeName
# required by the parameter: System.Management.ManagementClass#ROOT\cimv2\StdRegProv.
# At line:1 char:6
# + test $wmi
# + ~~~~
# + CategoryInfo : InvalidArgument: (:) [test], ParameterBindingArgumentTransformationException
# + FullyQualifiedErrorId : MismatchedPSTypeName,test
test $reg
# outputs: NameSpace: ROOT\cimv2
# Name Methods Properties
# ---- ------- ----------
# StdRegProv {CreateKey, Delet... {}
PowerShell V2测试:
function testv2 {
param(
[ValidateScript({($_ | Get-Member)[0].typename -eq 'System.Management.ManagementClass#ROOT\cimv2\StdRegProv'})]
$mine
)
$mine
}
testv2 $reg
# outputs: NameSpace: ROOT\cimv2
#
# Name Methods Properties
# ---- ------- ----------
# StdRegProv {CreateKey, Delet... {}
testv2 $wmi
# Error: testv2 : Cannot validate argument on parameter 'mine'. The "($_ | gm)[0].typename -eq 'System.Management.ManagementClas
# s#ROOT\cimv2\StdRegProv'" validation script for the argument with value "" did not return true. Determine why the valid
# ation script failed and then try the command again.
# At line:1 char:7
# + testv2 <<<< $wmi
# + CategoryInfo : InvalidData: (:) [testv2], ParameterBindingValidationException
# + FullyQualifiedErrorId : ParameterArgumentValidationError,testv2
这篇关于如何严格将变量键入为特定的WMI类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文