/\/\o\/\/ PowerShelled

This blog has moved to http://ThePowerShellGuy.com Greetings /\/\o\/\/
$AtomFeed = ("Atom.xml")
$PreviousItems = (" WMI help Part 2 "," Wmi-Help Part 1 "," Create System Variable From MSH (Part2) "," Create System Variable From MSH "," Setting the Path / system variables from MSH "," Obfuscated Monad Script "," Get Binary SID in MSH (Share Security Update) "," Replace Security on existing share using MSH "," Einstein "," Runas with loading Profile script in MSH "," ")

Saturday, November 05, 2005

 


WMI help Part 3 (Methods)



w.b

After getting all the WMI-classes in Wmi-Help Part 1
and getting the properties and Methods of a Single Class in WMI help Part 2

we are now ready to look a bit deeper into the Methods,

Again I made this into a function, , I did go a bit into Part 4 the execution already by generating a Template Script, but the plan for part 4 is to Bind the Method Execution to a WMI-instance. (using TypeData) as for the non-Static WMI Methods you need an Instance. (also explained later).

the Function can be Used like this :



MSH> gwm win32_share Create
First It shows you the In-parameters of the Method, and then a Sample script.
the sample script will be different depending upon the type of Method Static or non-Static.

I won't show all the output, but to show the difference between a Static and a not Static Method I will Show 2 Generated Scripts in the output after the Descriptions.

First a Static Method (gwm win32_share Create ), You need to fill in the Inparams into the Template :



# win32_share Create-Method Sample Script
# Created by Get-WmiMethodHelp
# /\/\o\/\/ 2005
# Fill InParams values before Executing
# InParams that are Remarked (#) are Optional

$Class = "win32_share"
$Method = "Create"
$MP = new-object system.management.ManagementPath
$MP.Server = "."
$MP.NamespacePath = "root\cimv2"
$MP.ClassName = $Class

$MC = new-object system.management.ManagementClass($MP)
$InParams = $mc.GetMethodParameters($Method)

# $InParams["Access"] = [object:Win32_SecurityDescriptor]
# $InParams["Description"] = [string]
# $InParams["MaximumAllowed"] = [uint32]
$InParams["Name"] = [string]
# $InParams["Password"] = [string]
$InParams["Path"] = [string]
$InParams["Type"] = [uint32]

"Calling win32_share : Create "

$R = $mc.InvokeMethod($Method,$Inparams,$Null)
"Result : "
$R
and Now the Delete Function, a Method that needs an instance (gwm win32_share Delete ),
as you can see This makes an Extra Variable $Name, this is the Key Property of the win32_share Class (automagicly the right property), that must be filled in before running the script, to build the Filter.
as the Delete Method takes no Parameters, the $inparms are not used (the line $inparms line is not needed in this Case but I wrote it to early in the Script.




# win32_share delete-Method Sample Script
# Created by Get-WmiMethodHelp
# /\/\o\/\/ 2005
# Fill InParams values before Executing
# InParams that are Remarked (#) are Optional

$Class = "win32_share"
$Method = "delete"
$Name = [string]

$filter = "Name = '$Name'"
$MC = get-WMIObject $class -filter $filter

$InParams = $mc.GetMethodParameters($Method)

"Calling win32_share : delete "

$R = $mc.InvokeMethod($Method,$Null)
"Result : "
$R

Now that we have seen wat it does, let's walk trough the code :

first you may notice the "if ($True){}"-blocks (as they resolve alway's TRUE, this may seem a bit useless), I use them to provide a different Trap for different blocks of Code, I did not find a way to do that outside of an IF-block.

next we get a # set options block that must look familiar if you did read the former posts.
Yes, we want Descriptions again, And this time we need some more Qualifiers, as we see later.

Next we make a ManagementScope ($MS) we don't realy need this as we are connecting to the Local Computer, but I use this later to Create a MangementPath used to generate a part of the Sample script to make it easy to change Computer.

And make a ManagementClass with the Options we created.(in the IF($true)-block to trap the error, if the Class does not exists)

In the Next block, we create a StringBuilder for creating a Template script, as we append to this template-script alot during the script, this is more efficient as a String as a string get's copied to a new string in .NET every time you change it.

Next the is an interesting check in the script, the check if the Method has a Static qualifier,
If the Method does not have one, it Needs an Instance to act upon.
Again I user a Trap here because if a Method is not Static the porperty is not FALSE but just not there.

As our Template script should be different depending on if the Method is Static (If not we need to get an Instance), I generate a different piece of code to put in the Stringbuilder($SB), depending on the type of the Method.If the Script is not Static I get the Key properties of the WMI-class to build the $Filter-String used in the Template Script to select the Instance.

Next interesting line in the script is this :



$inParam = $mc.Get_Methods()[$WMIMethod].get_InParameters()


This will get us the In Parameters of the Method. so we have an easy way to provide them to the Method.

in the next forEach-loop we wil check the Inparameters for the Following interesting Qualifiers next to the Description Qualifier :



$Optional = $_.get_Qualifiers()["Optional"].Value
$CIMType = $_.get_Qualifiers()["Cimtype"].Value

As the Optional qualifier, same as the Static Qualifier is not there if the property is not Optional, we will Trap the getting of the $Optional Qualifier.

Also Interesting here is the Following 2 Lines :



if ($Optional -eq $TRUE) {[void]$SB.Append('# ')}
[void]$SB.Append('$InParams["');[void]$SB.Append("$($_.Name)`"] = ");[void]$SB.AppendLine("[$CIMType]")


this Will write a Line in the SampleScript for Every Parameter in the Inparams of the Method, But Will Remark it when the Property is Optional, also it Will put the CIMType in the Line, so when filling in the Template we see what to fill in.


Next we have Another If Block:



If ($HasParams -eq $False)


this is because we need a different overload in the script if we have no Inparms.
(I leave the GetInparams function in the script as I did write it already more early in the script, but it is not needed in the Sample-Script if the Method has no parameters.)

At the End of the Script We use the $SB.ToString Method to write the Generated Script.

that was it, the error catching on the Qualifiers and the generating of the Sample Script, does make this script a bit more difficult to read then the former scripts, but i think is a nice start to build scripts for executing Methods.

gr /\/\o\/\/

*Edit* As I edited this Post the Pipeline Signs will be gone, but I posted an Update of the script here : MSH get-WmiMethodHelp (GWM) Update + format tips.

And the Complete Script :


# GetWmiMethodInfo.MSH
# Gets Method Parameters with descriptions from WMI class
# it also Creates an Example script.
# /\/\o\/\/ 2005

Function get-WMIMethodHelp{
Param ([string] $WmiClass = "",[string] $WmiMethod = "")
Trap{Break}
#Check Params
If($true) {
if ($wmiClass -eq "") {Throw "No WMIClass given"}
if ($wmiMethod -eq "") {Throw "No WMIMethod given"}
Trap{Break}
}

# Set Options

$opt = new-object system.management.ObjectGetOptions
$opt.UseAmendedQualifiers = $true

$MS = new-object system.management.ManagementScope

# IF block used to get Custom Error Handling

if ($true) {
$MC = new-object system.management.ManagementClass($MS,$WMIClass,$opt)
Trap{"Class not Found";Break}
}

#make a stringBuilder to make a Template Script

$SB = new-Object text.stringbuilder
[void]$SB.Append('$Class = "') ; [void]$SB.AppendLine("$WMIClass`"")
[void]$SB.Append('$Method = "') ; [void]$SB.AppendLine("$WMIMethod`"")

# if Static Qualifier is not present then Method Needs Instance

if ($True) {
$Static = $false
$Static = $mc.Get_Methods()[$WMIMethod].get_Qualifiers()["Static"].Value
Trap{$Static = $False;continue}
}

If ($static -eq $True) {

# MP is used to make it possible to choose a Computer in the generated Script
$MP = new-object system.management.ManagementPath($MS.Path.path)

[void]$SB.AppendLine('$MP = new-object system.management.ManagementPath')
[void]$SB.Append('$MP.Server = "') ; [void]$SB.AppendLine("$($MP.Server)`"")
[void]$SB.Append('$MP.NamespacePath = "') ; [void]$SB.AppendLine("$($MP.NamespacePath)`"")
[void]$SB.AppendLine('$MP.ClassName = $Class`n')
[void]$SB.AppendLine('$MC = new-object system.management.ManagementClass($MP)')

}Else {

# IF not static We need to provide The Key Properties
# so we can use them in the script to get the instance.

$Filter = ""
$mc.get_Properties() foreach {
$key = $false
$key = $_.get_Qualifiers()["key"].value
Trap{Continue}
If ($key -eq $True) {
$CIMType = $_.get_Qualifiers()["Cimtype"].Value
[void]$SB.AppendLine("`$$($_.Name) = [$CIMType]")
$Filter += "$($_.name) = `'`$$($_.name)`'"
}
}

[void]$SB.Append('`n$filter = ');[void]$SB.AppendLine("`"$filter`"")
[void]$SB.AppendLine('$MC = get-WMIObject $class -filter $filter`n')

}

[void]$SB.AppendLine('$InParams = $mc.GetMethodParameters($Method)`n')

# back to the Normal output

"$WMIClass : $WMIMethod :`n"
if ($true) {
$mc.Get_Methods()[$WMIMethod].get_Qualifiers()["Description"].Value
Trap{"Method not Found";Break}
}

"`n$WMIMethod Parameters :"
# get the Parameters

$inParam = $mc.Get_Methods()[$WMIMethod].get_InParameters()

$HasParams = $False
if ($true) {
$inParam.get_Properties() foreach {
$HasParams = $true
# if Optional Qualifier is not present then Parameter is Mandatory
if ($True) {
$Optional = $false
$Optional = $_.get_Qualifiers()["Optional"].Value
Trap{$Optional = $False;continue}
}
$CIMType = $_.get_Qualifiers()["Cimtype"].Value
"`nName = $($_.Name) `nType = $CIMType `nOptional = $Optional"

# write Parameters to Example script

if ($Optional -eq $TRUE) {[void]$SB.Append('# ')}
[void]$SB.Append('$InParams["');[void]$SB.Append("$($_.Name)`"] = ");[void]$SB.AppendLine("[$CIMType]")

$_.get_Qualifiers()["Description"].Value
}
trap{'[None]';$HasParams = $False;continue}
}

# Call diferent Overload as Method has No Parameters

If ($HasParams -eq $True) {
[void]$SB.AppendLine("`n`"Calling $WMIClass : $WMIMethod with Parameters :`"")
[void]$SB.AppendLine('$inparams.get_properties() select name,Value')
[void]$SB.AppendLine('`n$R = $mc.InvokeMethod($Method, $inParams, $Null)')

}Else{
[void]$SB.AppendLine("`n`"Calling $WMIClass : $WMIMethod `"")
[void]$SB.AppendLine('`n$R = $mc.InvokeMethod($Method,$Null)')
}
[void]$SB.AppendLine('`"Result : `"')
[void]$SB.AppendLine('$R')

# Write the Sample Script :

"`nSample Script :`n"
"# $WMIclass $WMIMethod-Method Sample Script"
"# Created by Get-WmiMethodHelp"
"# /\/\o\/\/ 2005"
"# Fill InParams values before Executing"
"# InParams that are Remarked (#) are Optional`n"

$SB.ToString()
}

set-alias gwm get-WMIMethodHelp



Comments:
Blogger DontBotherMeWithSpam
This comment has been removed by a blog administrator.
 
Blogger DontBotherMeWithSpam
gosh, you are progressing too fast for me and it's taking me a while just to catch up :)

great series there you are running :)

BTW, what kind of generator are you using to highlight your code?
 
Blogger /\/\o\/\/
Thx,
I also planned a week for this but as there was no opponent on my Chess game this week-end ;-( ... and MSH is just to great to play with ;-) ...

but as I not realy like the 3th script as is.(as the result is nice, I think, I find the code not clean enough, I'm a bit wrestling with the Errorhandling and the Flow of It.)

the rest will take me some more time.

for colorcoding I'm using CodeHTMLer
see also :

http://mow001.blogspot.com/2005/10/colorcoding-msh-scripts-on-blog.html

gr /\/\o\/\/
 
Post a Comment

Links to this post:

Create a Link



<< Home

Archives

October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006  

$Links = ("PowerShell RC1 Docs"," PowerShell RC1 X86"," PowerShell RC1 X64"," Monad GettingStarted guide"," Monad Progamming Guide"," Monad SDK"," Monad videos on Channel 9"," MSH Community Workspace"," scripts.readify.net "," MonadSource"," www.reskit.net"," PowerShell Blog"," Under The Stairs"," computerperformance powershell Home"," proudlyserving"," MSH on wikipedia"," MSHWiki Channel 9"," Keith Hill's Blog"," Precision Computing"," PowerShell for fun"," MSH Memo (Japanese)"," monadblog")

find-blog -about "PowerShell","Monad" | out-Technorati.
find-blog -contains "","" | out-Technorati.
Google
 
Web mow001.blogspot.com

This page is powered by Blogger. Isn't yours?