/\/\o\/\/ PowerShelled

This blog has moved to http://ThePowerShellGuy.com Greetings /\/\o\/\/
$AtomFeed = ("Atom.xml")
$PreviousItems = (" PowerShell RC2 and Active Directory Part 2 "," PowerShell : Hosting IronPython "," PowerShell RC2 and Active Directory "," PowerShell : Using IronPython to Connect to AD and... "," PowerShell Session video of Bruce Payette "," PowerShell : Active Directory Part 11 - moving - R... "," PowerShell : Learn about the HashTable Object and ... "," PowerShell : Setting SendAs permission in Exchange... "," PowerShell : Active Directory Part 10 (AD Browser) "," PowerShell "," ")

Sunday, October 01, 2006

 


PowerShell : WMI Support in RC2 (Series part 1)



 

As the WMI Support in PowerShell as also changed in RC2,

I will start a new WMI series by translating former WMI posts on my blog to PowerShell RC2, and I will show what has changed,

Opposed to what I think about the new Active Directory Support See :  PowerShell RC2 and Active Directory Part 2 ,

In this Case I think the wrapper does add value, here also a bit more PSBase is needed, but the added functional in this case I think is much more as what the ADSI wrapper does and I has much less impact on working interactively  ,

So for now I decided I like it, or working with it and the translating of older WMI post in this series, does bring up some hidden problems,

I will start with the First WMI example I did on my blog (Lets Query WMI from MSH) in the first Month October 2005 about  RelatedObjectQuery 's  in WMI,

as I was just starting then with Monad (Codename for PowerShell at that time), and did go on from a VbScript Example, I did copy the old post and will follow it in RC2  in this re-post and I will translate the scripts inbetween the old text adding comments and changes to it (Italic)., also I will show the use of out-PropertyGrid  PowerShell : out-PropertyGrid  that is very handy for editing the WMI Queries in a GUI Form (load windows forms library first see example).

here is the edited post :

Lets Query WMI from MSH

*Original text*

ls, as I was answering a post in the NG, about a vbscript to get dependent services the (corrected) script looks like this :

Dim UnArgs
Set UnArgs = WScript.Arguments.Unnamed
WScript.Echo UnArgs(0)

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
& "{Win32_Service.Name='" & UnArgs(0) & "'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Antecedent" )

for each s in colServiceList
WScript.Echo s.name
next
this is a bit more as the standard WMI get propery, and involves more than 1 WMI-class. I decided to make it in MSH also :. at first I came with this :
Function GetDep {
$mos = (new-object system.management.ManagementObjectSearcher)
$mos.Query = "Associators of {Win32_Service.Name='" + $Args[0] + "'} Where AssocClass=Win32_DependentService Role=Antecedent"
$mos.get()
}

 


* Update *


As you can see, if you past this script into the PowerShell RC2 Console it still works  :


 



PS C:\PowerShell> Function GetDep {
>> $mos = (new-object system.management.ManagementObjectSearcher)
>> $mos.Query = "Associators of {Win32_Service.Name='" + $Args[0] + "'} Where AssocClass=Win32_DependentService Role=A
ntecedent"
>> $mos.get()
>> }
>>
PS C:\PowerShell> getdep 'lanmanserver'

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK



But in PowerShell RC2 we can use the  [WmiSearcher]  "intrinsic type" (From Release notes) ,  so I did started out testing interacive in the PowerShell Conole 


 



PS C:\PowerShell> [wmiSearcher]("Associators of {Win32_Service.Name='" + $Args[0] + "'} Where AssocClass=Win32_DependentService Role=Antecedent")

Scope : System.Management.ManagementScope
Query : System.Management.ObjectQuery
Options : System.Management.EnumerationOptions
Site :
Container :

PS C:\PowerShell> ([wmiSearcher]"Associators of {Win32_Service.Name='lanmanserver'} Where AssocClass=Win32_DependentService Role=Antecedent").get()

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK


also I would do some things a bit different now, here is the translated script for PowerShell RC2 :


 



# PowerShell RC2 Function to get Services that depent on the given ServiceName

Function Get-DependentService ([String]$ServiceName) {

  $WmiSearcher = [wmiSearcher]"Associators of {Win32_Service.Name='$ServiceName'} Where AssocClass=Win32_DependentService Role=Antecedent"
  $WmiSearcher.get()

}

You can See I changed to a Named Parameter for the service Name to make things more clear, opposed the $Args[0] I did use in the Monad examples , and I did a make use of the Variable handling of PowerShell that will expand in double quoted strings but both where possible at that time also (You can see that I was using a more VbScript way as I was just starting out with PowerShell at that time and still did "think VbScript"  as I was less used to PowerShell) ,


The Difference in RC2 is the [WmiSearcher]  "intrinsic type" , so it is not needed anymore to use new-object system.management.ManagementObjectSearcher to get the .NET object , also the next remark in the Original is Covered in RC2 :


 



PS C:\PowerShell> [WMI]'\\MOWDC001\root\cimv2:Win32_Service.Name="lanmanserver"'

ExitCode : 0
Name : lanmanserver
ProcessId : 876
StartMode : Auto
State : Running
Status : OK


the rest is all still working only you need to use PSBase as with the [adsi] wrapper, but this time the wrapper shows the Methods of the Win32_Share class and we can invoke them directly, we  see  the methods of the WMIclass in the Get-Member and have Tab Completion for them and this is very handy


As we needed to Invoke them in PowerShell before RC2 , and could not see them, so in this case the wrapper has much more added value.


 



PS C:\PowerShell> (get-wmiObject win32_service -filter "Name = 'lanmanserver'") | gm

TypeName: System.Management.ManagementObject#root\cimv2\Win32_Service

Name MemberType Definition
---- ---------- ----------
Change Method System.Management.ManagementBaseObject Change(System.String DisplayName, System...
ChangeStartMode Method System.Management.ManagementBaseObject ChangeStartMode(System.String StartMode)
InterrogateService Method System.Management.ManagementBaseObject InterrogateService()
PauseService Method System.Management.ManagementBaseObject PauseService()
ResumeService Method System.Management.ManagementBaseObject ResumeService()
StartService Method System.Management.ManagementBaseObject StartService()
StopService Method System.Management.ManagementBaseObject StopService()
UserControlService Method System.Management.ManagementBaseObject UserControlService(System.Byte ControlCode)

...

 

PS C:\PowerShell> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").PsBase | gm

TypeName: System.Management.Automation.PSMemberSet

Name MemberType Definition
---- ---------- ----------
add_Disposed Method System.Void add_Disposed(EventHandler value)
Clone Method System.Object Clone()
CompareTo Method System.Boolean CompareTo(ManagementBaseObject otherObject, Compariso...
CopyTo Method System.Management.ManagementPath CopyTo(ManagementPath path), System...
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
Delete Method System.Void Delete(), System.Void Delete(DeleteOptions options), Sys...
Dispose Method System.Void Dispose()
Equals Method System.Boolean Equals(Object obj)
Get Method System.Void Get(), System.Void Get(ManagementOperationObserver watcher)
GetHashCode Method System.Int32 GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetMethodParameters Method System.Management.ManagementBaseObject GetMethodParameters(String me...
GetPropertyQualifierValue Method System.Object GetPropertyQualifierValue(String propertyName, String ...
GetPropertyValue Method System.Object GetPropertyValue(String propertyName)
GetQualifierValue Method System.Object GetQualifierValue(String qualifierName)
GetRelated Method System.Management.ManagementObjectCollection GetRelated(), System.Ma...
GetRelationships Method System.Management.ManagementObjectCollection GetRelationships(), Sys...
GetText Method System.String GetText(TextFormat format)
GetType Method System.Type GetType()

...


I will cover the Methods in  more detail in later posts in this Series, for the following examples we need to add  PSBase at some places, for the rest it works the same only we can start the Query we constucted much easier , see next update below following the original text how the use the Query in RC2 , here is how it looks in RC2 with PSbase before the method, but first the example on how the change the original code  :.

 


PS C:\PowerShell> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").PSBase.GetRelated($null,"Win32_DependentService",$null,$null,$null,"Antecedent",$false,$null)

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK


 

*Original text*


(you can not use a Moniker to connect to WMI as in VBscript) But after that I thought .. this may be correct but not realy MSH. Hence, I did look at the get-WMIObject function. first how to get only the wanted Class. the get-WMIObject uses - filter for this :



then how to get the related class


a Get-Method on the Object revealed the GetRelated Property


hence ,


Function GetServiceDeps {($s = get-wmiObject win32_service -filter "Name = '$($args[0])'").GetRelated("win32_service")}



And Ready ..


Much more Clean, shorter and more MSH



but then again .....maybe NOT..... (c) LSL


I did forget the Role-part this does not matter for "lanmanserver" so I did not see it at first but this will give also the relations the service is dependend on.



OK, lets look again at that Method :




MSH G:\Monad> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").GetRelated.OverloadDefinitions
System.Management.ManagementObjectCollection GetRelated()
System.Management.ManagementObjectCollection GetRelated(String relatedClass)
System.Management.ManagementObjectCollection GetRelated(String relatedClass, String relationshipClass, String relationshipQualifier, String relatedQualifier,String relatedRole, String thisRole, Boolean classDefinitionsOnly, EnumerationOptions options)
(I left out the ASync Methods)
Oops, IMNSHO that is not a nice Overload !!!
(Quiz Question : You know them All  well enough to fill the 3th overload ?)
I do now ;-) (see later in post) and it seems that you can keep the ones you don't need empty.
it is : 
MSH G:\Monad> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").GetRelated($null,"Win32_DependentService",$null,$null,$null,"Antecedent",$false,$null)
But then I did not know what to fill in, but I saw another Method called

after playing a bit I stopped at :

 ((($s = get-wmiObject win32_service -filter "Name = 'lanmanserver'").GetRelationships("win32_Dependentservice"))  foreach {$_.dependent}).split("=")[1]

What do you think ? , In this case I would more like the ".NET" solution ;-) But.. help was on the way ;-) while searching SDK's etc for the WQL language specs, I stumbled upon System.Management.RelationshipQuery after playing with it (more about how later) I could only make a

So I needed his brother-class : System.Management.RelatedObjectQuery(System.Management.RelatedObjectQuery is related to GetRelated and RelationshipQuery to GetRelationships)


.So ... and what can we do with thos 2 classes ?


Translate WQL Query's to Properties and Back !!!


MSH G:\Monad> $roq = new-object System.Management.RelatedObjectQuery
MSH G:\Monad> $roq.QueryString = "associators of {Win32_Service.name='lanmanserver'} where resultclass = win32_service role = Antecedent"
MSH G:\Monad> $roq


IsSchemaQuery : False
SourceObject : Win32_Service.name='lanmanserver'
RelatedClass : win32_service
RelationshipClass :
RelatedQualifier :
RelationshipQualifier :
RelatedRole :
ThisRole : Antecedent
ClassDefinitionsOnly : False
QueryLanguage : WQL
QueryString : associators of {Win32_Service.name='lanmanserver'} wher
e resultclass = win32_service role = Antecedent
So, Now you know How I filled in that 3th Overload of GetRelated ;-) but at the End, I don't know if i want to, because you can get put the RelatedObjectQuery into a ManagementObjectSearcher directly. (see last "bonus"-script.) so until you need more as only the relatedClass (1st/2nd Overload of GetRelated) get-wmiObject is nice but after that I prefer the "system.management"-Way And .. as final "Bonus" - script to learn the WMI Queries, I coupled to on my Objectviewer-script, to get a GUI WQL-Querytool :
$roq = new-object System.Management.RelatedObjectQuery
ov($roq)
$mos = new-object system.management.ManagementObjectSearcher($roq)

In the MSHObjectviewer you can change the Properties (or the Query), and you will see the effect in the Query(or the properties). You have to change to another field to see the reaction. I think now you have enough tools to get some more heavy work done in WMI Doe er iets leuks mee (have Fun) gr /\/\o\/\/ PS IF you do not have OV(MSHObject-Viewer), go here : MSH Object Viewer for more info about WQL queries go to : http://msdn.microsoft.com/library/en-us/wmisdk/wmi/wql_sql_for_wmi.asp?frame=true


 


* Update *


Also for the .NET Query helper classes I did show how to use in the original post above, you can use them with [WmiSearcher]  in RC2 so you do not need to make the object yourself,


Also I show that you can also use a GUI using the function out-datagrid to get a kind of Query Generator,


You can find that function here :


  powershell-out-propertygrid-msh-view.html 


that is an updated version of the MSH object viewer mentioned. that can be used to configure the WMI queries in A GUI


 



PS C:\PowerShell> # make the Query
PS C:\PowerShell>
PS C:\PowerShell> $roq = new-object System.Management.RelatedObjectQuery
PS C:\PowerShell> $roq.QueryString = "associators of {Win32_Service.name='lanmanserver'} where resultclass = win32_service role = Antecedent"
PS C:\PowerShell> $roq

IsSchemaQuery : False
SourceObject : Win32_Service.name='lanmanserver'
RelatedClass : win32_service
RelationshipClass :
RelatedQualifier :
RelationshipQualifier :
RelatedRole :
ThisRole : Antecedent
ClassDefinitionsOnly : False
QueryLanguage : WQL
QueryString : associators of {Win32_Service.name='lanmanserver'} where resultclass = win32_service role = Antecedent

PS C:\PowerShell>
PS C:\PowerShell> # Execute the Query in RC2 :
PS C:\PowerShell>
PS C:\PowerShell> ([WmiSearcher]$roq).get()

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK

 


 


 


PS C:\PowerShell>
PS C:\PowerShell> # Example Of using a PropertyGrid to make the Query
PS C:\PowerShell>
PS C:\PowerShell> [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")


GAC Version Location
--- ------- --------
True v2.0.50727 C:\WINDOWS\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.For...

PS C:\PowerShell>
PS C:\PowerShell> . .\Out-PropertyGrid.ps1
PS C:\PowerShell>
PS C:\PowerShell> $roq | opg
Cancel
PS C:\PowerShell> # And you can also use it for the whole Searcher Object
PS C:\PowerShell> [WmiSearcher]$roq | opg
Cancel
PS C:\PowerShell>


 

 

the [WMI] and [WMIClass] in PoSH RC2 make working with a WMI Path or Query much Easier,also that you can see the Class methods on the WMI Object and use the directly, make that it is much Easier to work with and explore WMI in PowerShell RC2,

So in this examples the RC2 changes do really help, and Queries are more used, and more handy to work with as using the methods as you see in this post, 

Hence in Case of WMI till now I'm still very happy with the change, as you can see in original entry I missed that at the time, and can live with PSBase for this.

So I don't mind I need to update my scripts for this, more later in this series.

Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




Comments: Post a Comment



<< 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?