How do I strictly-type a variable as a specific WMI class?

前端 未结 1 600
清歌不尽
清歌不尽 2021-01-07 01:55

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

相关标签:
1条回答
  • 2021-01-07 02:36

    Can you do this?

    Param (
        [PsTypeName("System.Management.ManagementClass#ROOT\namespace\class_name")]
        $Class
    )
    

    Or if using CIM instead of WMI, this:

    Param (
        [PsTypeName("System.Management.Infrastructure.CimInstance#root/namespace/class_name")]
        $Class
    )
    

    TEST CASE:

    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 Test:

    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
    
    0 讨论(0)
提交回复
热议问题