On the scriptcenter on Technet, you can find information about the Windows PowerShell Week
by the Scripting Guy , a series of webcasts about PowerShell, to be held November 6-10.
Don't miss it !
Enjoy,
Greetings, /\/\o\/\/
Tags : Monad PowerShell
Hey PowerShell Guy : How Can I Split a String Only on Specific Instances of a Character?
PoSH>[regex]::Split("aaa&bbb&ccc&aamp;ddd","&(?!amp)")
aaa
bbb&ccc
aamp;ddd
Enjoy,
Greetings, /\/\o\/\/
Tags : Monad PowerShell
Hey PowerShell Guy : How Can I Tell Whether a Number is Even or Odd?
Function check-even ($num) {[bool]!($num%2)}
PoSH>check-even 12
True
PoSH>check-even 13
False
Enjoy,
Greetings, /\/\o\/\/
Tags : Monad PowerShell
I realy added a lot on my TabCompletion :
this function realy makes PowerShell fly for me :
***
*Edit* I made beter version of this script on my new
blog : The PowerShell Guy ( http://ThePowerShellGuy.com )As it comes with an installer its much more easy to
setup,
and it uses one database for all data, it works mostly the
same as this oneJust download the PowerTab.ZIP file from the overview page here :
http://thepowershellguy.com/blogs/posh/pages/powertab.aspx
run PowetTabSetup.Ps1 and you are ready to go
***
I will Post my current TabCompletion below, I contains a lot of additions I realy like and the GUI selecting of items in a list I think is handy also as
Some of the additions in this version might be to specific, could be constructed better or are not consistent, but this version is my own current version as it has grown I and might need some cleaning up, but I posted this version for trying out and to tweak it to your need or to get some ideas and to get you started on Custom tab completion, or just use it as is .
As I think*Note* this script is also on Codeplex in : PowerShell Utility scipts as my last version this works as is.
For this version to work you need some preparement as it needs some utility scripts and a XML file to work, the code to make the XML file is needed only once, the loading of it needs to be done every time a new shell is started, so it is best placed in your profile: (for testing if you past in all of the codeblocks your also ready to go),
Utility Functions (to be called in profile)
Then you need to build the Tab Completion DataBase for first use.
Build XML file (one time only needed)
as you can see here, after we did initial fill it we can use the functions to customize it and then save it again,.I also added 2 functions to update the Alias and Function list.
Also as te Tabcompletion function uses a GUI you need to load this help function also :
Out-DataGridView needed loaded for tabcompletion (profile)
*edit* needed formas library :
And after that ofcourse load the TabCompletion replacement : TabCompletion Function (load in profile)
# Alias
PoSH> gwmi[tab]
PoSH> Get-WmiObject win32_sh[tab]
Posh> Get-WmiObject Win32_Share# Function + CmdLet (on -)
PoSH> get-t[tab]
PoSH>Get-tabCompletion# Function + CmdLet (on %)
PoSH>ref%[tab]
PoSH>Refresh-TabCompletionAlias# GUI tabcompletion :
PoSH>w_sh[tab]
PoSH>f_[tab]
PoSH>w_ [tab]# Custom
PoSH>ls %[tab]
PoSH>ls foreach-object {}# () resolving
PoSH>(LS).[tab]
PoSH>(gwmi win32_share).[tab]
Enjoy,
Greetings, /\/\o\/\/
Tags : Monad PowerShell
you can double click the clock in the systray to do a quick lookup (I often used it for that) but you need to be an Admin to do so, so it is not available on my own workstation using my normal account , also it shows no week numbers and I often need those also
So this trick did help me out on several occasions, but still this is not a really ideal solution.
Hence I made this small PowerShell function that does show a Calendar with WeekNumbers in a Form that closes again on hitting [Enter], that I load in my profile and alias to Cal to keep it ready for a quick lookup of some dates, as you will be surprised how often it comes handy.
(note the dot-space to load in global scope, and the loading forms library in profile (needed for function)
to test you can also just past the code into the PowerShell console to load the function, and start using the function:
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
. c:\PowerShell\Functions\GetCalendar.ps1
and here is the script : (formatted by the html export function from PowerShell Analyzer a great PowerShell editor, if you not know it yet be sure to try it out)
# Function Get-Calendar
# Shows a calendar with WeekNumbers in a Form
# /\/\o\/\/ 2006
# www.ThePowerShellGuy.com
Function get-Calendar {
$form = new-object Windows.Forms.Form
$form.text = "Calendar"
$form.Size = new-object Drawing.Size @(656,639)
# Make "Hidden" SelectButton to handle Enter Key
$btnSelect = new-object System.Windows.Forms.Button
$btnSelect.Size = "1,1"
$btnSelect.add_Click({
$form.close()
})
$form.Controls.Add($btnSelect )
$form.AcceptButton = $btnSelect
# Add Calendar
$cal = new-object System.Windows.Forms.MonthCalendar
$cal.ShowWeekNumbers = $true
$cal.MaxSelectionCount = 356
$cal.Dock = 'Fill'
$form.Controls.Add($cal)
# Show Form
$Form.Add_Shown({$form.Activate()})
[void]$form.showdialog()
# Return Start and end date
return $cal.SelectionRange
}
set-alias cal get-Calendar
So if you are need a quick calendar, you just need ro do a quick cal[enter], in the PowerShell console ..and there you go :
PoSH>cal
End Start
--- -----
10/12/2006 12:00:00 AM 10/12/2006 12:00:00 AM
and you can select a timeframe in the calendar to return.
I added a "hidden" button (size 1 by 1) , to handle the [enter] key to close the Form and return the start and end date, to make the calendar more handy to use, as a quick enter will close the form after use and you do not need to use X to close the form, and I still can use fill on the Calendar control. also you can select a range of days in the Calendar and the function will return the Start and the End date of that period to the PowerShell console when it is closed.
PoSH>$vacation = cal
PoSH>$vacation.endSunday, November 05, 2006 12:00:00 AM
PoSH>$vacation.start
Saturday, October 14, 2006 12:00:00 AM
PoSH>$vacation.end - $vacation.start
Days : 22
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 19008000000000
TotalDays : 22
TotalHours : 528
TotalMinutes : 31680
TotalSeconds : 1900800
TotalMilliseconds : 1900800000
Enjoy,
Greetings, /\/\o\/\/
Tags : Monad PowerShell
For some actions in WMI you need to enable privileges , for example for the SetDateTime method of win32_operatingsystem,
and how you can use the GUI again to edit settings, and change Classes , and also see posible values of properties also with the searcher you can do the same as we did see in (" PowerShell : WMI Support in RC2 (Series part 2) "," PowerShell : WMI Support in RC2 (Series part 1) ","
[WmiSearcher]$roq | opg
as I did get a question by G/\/\E on the second part of this series, I did this quick post about this *Remark* I did not see the blog item he did make about this, about this when I started this
to see about that strange timeformat see second example, More information about calling methods in next post
PoSH>$win32_Operatingsystem = gwmi win32_Operatingsystem
PoSH>$win32_Operatingsystem.SetDateTime("20061010234615.000000+120")
Exception calling "SetDateTime" : "Access denied "
At line:1 char:35
+ $win32_Operatingsystem.SetDateTime( <<<< "20061010234615.000000+120")
PoSH>$win32_Operatingsystem.psbase.ScopeIsConnected Options Path
----------- ------- ----
True System.Management.ConnectionOptions \\localhost\root\cimv2PoSH>$win32_Operatingsystem.psbase.Scope.options
Locale :
Username :
Password :
Authority :
Impersonation : Impersonate
Authentication : Unchanged
EnablePrivileges : False
Context : {}
Timeout : 10675199.02:48:05.4775807
PoSH>$win32_Operatingsystem.psbase.Scope.options.EnablePrivileges = $true
PoSH>$win32_Operatingsystem.SetDateTime("20061010234615.000000+120")__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
Here you can see that you can also use the out-PropertyGrid to Edit and test those Settings as I showed in former posts about queries (Change properties and query will be automatically changed), *Note* you need to change to WmiClass eg to win32_share and back Note the changing of paths in the GUI, to reconnect and enable the privileges, note that you have a complete WMI browsel like this,
also I show the use of a added utility property added to a WMI class in RC2 to get a WMI dateTime, a bit more about methods in next post
PoSH>$win32_Operatingsystem = gwmi win32_Operatingsystem
PoSH>$win32_Operatingsystem.ConvertfromDateTime("10/10/2006 23:26:15")
20061010232615.000000+120PoSH>$win32_Operatingsystem.SetDateTime("20061010232615.000000+120")
Exception calling "SetDateTime" : "Access denied "
At line:1 char:35
+ $win32_Operatingsystem.SetDateTime( <<<< "20061010232615.000000+120")
PoSH>$win32_Operatingsystem | opg
CancelPoSH>$win32_Operatingsystem | opg
Cancel
PoSH>$win32_Operatingsystem.SetDateTime("20061010232615.000000+120")__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
Enjoy,
Greetings, /\/\o\/\/
Tags : Monad PowerShell
In last post PowerShell : WMI Support in RC2 (Series part 1) , I started out translating the first WMI post, about more advanced WMI queries, and the helperObjects ( RelatedObjectQuery and RelationshipQuery ) you could use as helpers for creating this kind of Queries .
Also I did show that you could use out-PropertyGrid to Edit and test those queries (Change properties and query will be automatically changed)
This is a great help in doing that advanced queries, but might be a step to much if you are just starting out with PowerShell and/or WMI
In this post I take a step back, and will first cover the different ways to get to just one WMI object / Class, and go on from the Lanman example in last post.
After that I will cover Next post I did on my blog also in October last year the WMI viewer script WMI viewer script for MSH (GUI) .
As I already made a out-DataGrid function here : PowerShell out-DataGrid update and more Dataset utilities that can take all sorts of input and show it in a GUI Form with a DataGrid that is a more generic solution, and can also combine datasources , (See Screendumps here : MSH GUI Viewer for Dataset Example ,) , Hence we do not really need it anymore, and also I could replace the whole first Part with "gwmi $WmiClass | "
PS C:\PowerShell> gwmi win32_service | out-DataGrid
Cancel
PS C:\PowerShell> gwmi win32_service | select [a-z] | out-DataGrid
Cancel
but I did still update the script and did put it at the end of this post as it uses the next change in RC2 getting to a static Class, and can take it as input, getting to static classes is much easier in RC2 but more about that in next post.
(we going to use that also in next post about using methods in RC2)
take a note about how I changed the input Parameter to [WmiClass] so it gets more flexible, it will not only take a string but anything it can translate to an WmiClass, so you can also pass it an (Variable with) WMI Class as input, also see I use a Class to get Instances from them not needed in this example but in next post I will show some more examples about using this :
PS C:\PowerShell> get-WMIDatagrid win32_share
Cancel
PS C:\PowerShell> [WmiClass]'win32_share'Win32_Share
PS C:\PowerShell> $WmiClass = [WmiClass]'win32_share'
PS C:\PowerShell> get-WMIDatagrid $WmiClass
Cancel
PS C:\PowerShell>
For More information about working with DataSets and Tables see my CSV series :
working with CSV files in MSH (part one)
/\/\o\/\/ PowerShelled: working with CSV files in MSH (part two)
/\/\o\/\/ PowerShelled: more Monad scripts, and a bit more CSV
And for using datasets with other datasources see these posts :
Access :
scripting games Last Day MSH answers for event 7 and 8
Excel :
Using ADO to get data from Excel to Dataset in Monad.
SQL (SQL Provider)
Getting and Working With SQL Server data in Monad
But to go on with WMI here are some way's to to get to an instance of a WMI class, I will show how to use get-WmiObject and also the new ways in PowerShell RC2 using [WMI] (name or Path) or [WmiSearcher] use a WQL query.
As last example I show using [WmiClass] like in the script, as I can only filter client site this is not a good way to do this, but I added it as an first example of the [WmiClass] (see also how it is used in the Updated script, to make the input more flexible and note other ways to do it)more in next post.
# Use get-WmiObject
PS C:\PowerShell> get-wmiObject win32_service -filter "Name = 'lanmanserver'"
ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK# a More Short way
PS C:\PowerShell> gwmi win32_service -f "Name = 'lanmanserver'"
ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK# Using [WMI] and a Path
PS C:\PowerShell> [WMI]'\\.\root\cimv2:Win32_Service.Name="lanmanserver"'
ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK# only the Name of the Class
PS C:\PowerShell> [WMI]'Win32_Service.Name="lanmanserver"'
ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK# Using a [WMISearcher] for using a WQL query to get to the Object
PS C:\PowerShell> [wmiSearcher]"Select * from Win32_Service where Name='lanmanserver'"
Scope : System.Management.ManagementScope
Query : System.Management.ObjectQuery
Options : System.Management.EnumerationOptions
Site :
Container :PS C:\PowerShell> ([wmiSearcher]"Select * from Win32_Service where Name='lanmanserver'").get()
ExitCode : 0
Name : lanmanserver
ProcessId : 876
StartMode : Auto
State : Running
Status : OK# Note that you can use get-Services in PowerShell but this uses .NET not WMI
PS C:\PowerShell> get-service lanmanserver
Status Name DisplayName
------ ---- -----------
Running lanmanserver ServerPS C:\PowerShell> get-service lanmanserver | gm
TypeName: System.ServiceProcess.ServiceController
Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = ServiceNamePS C:\PowerShell> [wmiClass]'win32_service'
Win32_Service
# Using WmiClass (filter client site not efficient)
PS C:\PowerShell> $win32_service = [wmiClass]'win32_service'
PS C:\PowerShell> $win32_service.psbase.GetInstances() |? {$_.name -eq 'lanmanserver'}ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK
You can see that RC2 makes you very flexible, Here the updated script using [wmiClass] directlyin the Parameter set.
for the Rest I only added a couple of PsBases and changed the topmost hack .
More very cool RC2 WMI stuff in next part of this series about calling WMI Methods !!, there the real power of the changes made in WMI will show !
Enjoy,
Greetings, /\/\o\/\/
Tags : Monad PowerShell
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 :
*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 UnArgsthis 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 :
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
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 : OKExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OKExitCode : 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 : OKExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OKExitCode : 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 : OKExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OKExitCode : 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]
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.RelatedObjectQuerySo, 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 :
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
$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> $roqIsSchemaQuery : 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 = AntecedentPS 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 : OKExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OKExitCode : 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
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