Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, February 15, 2016

Using Invoke-CIMMethod

In my PowerShell class last week, we took a lab a bit further.  This lab involved using the old WMI commands.  Well, that is no fun.  I was providing my answers to the lab using the new CIM cmdlets. I did this once before, but I forgot to update my answers.  You see, there is a difference in how you provide information to Invoke-CIMMethod and Invoke-WMIMethod

The objective was to change the Start Mode of the WinRM service.  To do this in WMI:

       Get-WmiObject –Class Win32_Service –Filter "Name='WinRM'" |
           Invoke-WmiMethod –Name ChangeStartMode –Argument 'Automatic'

You would think that you could do the same with the CIM cmdlets, but PowerShell did not like this.
     Get-CimInstance -ClassName Win32_Service –Filter "Name='WinRM'" |
        Invoke-CimMethod -MethodName ChangeStartMode -Arguments 'Automatic'
Invoke-CimMethod : Cannot bind parameter 'Arguments'. Cannot convert the "Automatic" value of type
"System.String" to type "System.Collections.IDictionary".
At line:2 char:65
+ ...   Invoke-CimMethod -MethodName ChangeStartMode -Arguments 'Automatic'
+                                                               ~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-CimMethod], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Management.Infrastructure.CimCmdlets.I
   nvokeCimMethodCommand

Using Invoke-CIMMethod, the –Arguments parameter requires a System.Collections.IDictionary object.  Say what???? So, I took a look at the MSDN documentation for System.Collections.IDictionary.  In the Remarks section, I learned that this object is simply a key/value pair. 

My next stop was Win32_Service on MSDN. In particular, the ChangeStartMode method of the Win32_Service class. Here I found out the key is StartMode and the value is Automatic.



Now all that is left is to correctly format my command line.
     Get-CimInstance -ClassName Win32_Service –Filter "Name='WinRM'" |
      Invoke-CimMethod -MethodName ChangeStartMode -Arguments @{startmode='Automatic'}


The –Arguments parameter is now a key/value pair.

No comments: