Showing posts with label WMI. Show all posts
Showing posts with label WMI. Show all posts

Saturday, March 02, 2013

WMI Explorer–Where’s It Gone–A Temporary Solution

As a trainer, teaching PowerShell, I use WMI Explorer heavily. For those who may be unfamiliar, this is a PowerShell script that displays information about WMI on a system. Written by MOW, a PowerShell MVP, it is for me the best tool I can find for displaying WMI data to the class.
The bad news is that for some reason, it’s old home is not resolving – so all the search engine listings point to a host that for some reason is not there.

In the meantime, I’ve put a copy here: https://docs.google.com/document/d/1kuyoyFSc-wNRZBZjWI3aNjIMdw48hYS9Av4S_iNMBwI/edit?usp=sharing

Tuesday, November 01, 2011

Introduction to WMI and PowerShell – A NEW Pluralsight Course

I am quite pleased to be able to announce I’ve finished my first video class for Pluralsight, Introduction to WMI and PowerShell. It’s now available for viewing for Pluralsight subscribers.  I’ve been watching it a bit this morning and it’s not bad, if I do say so myself. Smile

The course is a total of 2:29, and is broken down into 5 modules as follows:

  • Introduction to WMI and PowerShell (21:28) – Describes WMI in Windows and discusses some of the key WMI exploration tools. The module then looks at PowerShell support for WMI in PowerShell V3, and describes the WMI cmdlets. The module finishes with some of the gotchas you need to be aware of when using WMI with PowerShell.
  • Using PowerShell and WMI  (34:37) This module looks at accessing WMI data, including instances, instance properties and methods, WMI classes, and static class methods. We cover the use of the key WMI cmdlets and explain the use of Type Accelerators.
  • Practical PowerShell (24:42)  - This module looks at the range of data you can use in WMI. We show key namespaces and key classes you might leverage. The module also looks at some of the security settings you might make use of when using WMI in a Enterprise environment.
  • Using WMI Query Language (29:36) – Describes the WMI Query Language and how to use it with the PowerShell WMI cmdlets.
  • WMI Eventing (39:16) - This final module looks at accessing WMI events. It shows how to create both temporary and permanent event subscribers for intrinsic, extrinsic, and timer events. It also explains all those terms and shows how to leverage WMI’s eventing subsystem.

So if you are currently a Pluralsight subscriber, why not consider it? If nothing else, take the free trial – 10 days access to the entire library, including this course.

And also: a big thank you to Alexandar Nikolic (@alexandair on Twitter) for his proof reading of the course – much appreciated!!

Thursday, October 27, 2011

Pluralsight WebCast on Using WMI from PowerShell

I got a fun call last night – PluralSight has a regular webcast but this week’s presenter has had personal issues – and would I like to do the webcast? Well SURE!  When don’t I like the chance to talk about PowerShell!?!?

As it turns out, this is perfect timing - I’ve just finished developing a new PluralSight course, Using WMI from PowerShell which goes LIVE today. So this web cast is a great opportunity to tell you a bit more about the course, and hopefully tempt you to download it and consume the video! I’ll enjoy talking about it!!

The webcast is at 11:00 US Eastern Time – 16:00 time here in the UK. Please join us at: http://www.pluralsight-training.net/microsoft/Webcasts

Friday, October 07, 2011

Using PowerShell with WMI Events

I’ve been working on a WMI and PowerShell video course for PluralSight (due out soon) and am today working on the last bit of the course which covers Events. I found an MSDN sample written in VBScript. Here’s the VBScript:

Sub SINK_OnObjectReady(objObject, objAsyncContext)
    WScript.Echo (objObject.TargetInstance.Message)
End Sub

Set objWMIServices = GetObject( _
    "WinMgmts:{impersonationLevel=impersonate, (security)}") 

Set sink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")
 
objWMIServices.ExecNotificationQueryAsync sink, _
    "SELECT * FROM __InstanceCreationEvent " & _
    "WHERE TargetInstance ISA 'Win32_NTLogEvent' "
I spent some time looking at this trying to get my head around what it was actually doing.   Turns out that translating it into PowerShell was fairly simple. Here’s the PowerShell code:

$query = "SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent' "

Register-WmiEvent -Source Demo1 -Query $query -Action {
                Write-Host "Log Event occurred"
                Write-Host "EVENT MESSAGE"
                Write-Host $event.SourceEventArgs.NewEvent.TargetInstance.Message}

Even with the nice spacing that turns 9 hard to understand lines of VB SCript into 2 LONG lines of PowerShell (or 5 as it’s so nicely spaced out here). I could have written it as a one-liner had I wished to go for compactness – but I think spacing it out a bit helps in terms of understaning.

The bottom line for me is that PowerShell is just so much easier to understand – you register for an event. A query tells you which event. And when that event fires, you take some action. Job done.

Technorati Tags: ,

Thursday, September 22, 2011

Using PowerShell and WMI to Manage the Registry

For those of you who are very keen eyed, you may have noticed some posts on my PowerShell Scripts blog related to the WMI Registry Provider. I’ve been working on a PowerShell and WMI course which will be published by Plural Sight in October. As part of this, I have been playing with WMI and the Registry provider, which you can easily use via PowerShell.

Microsoft has implemented a nice registry provider withing WMI: the StdRegProv class in the ROOT\DEFAULT WMI class.  This class contains 20 static methods that enable you to perform any Registry action on a local or remote computer. You can access these in two ways, either using New-Object to create a new System.Management.ManagementClass object, specifying the path to the class to the constructor ("Root\default:StdRegProv"). Alternatively, you could use the [WmiClass] Type Accelerator, specifying [WmiClass]"Root\default:StdRegProv". Both return the class object, which contains a number of methods as shown here:

c:\> $x=new-object System.Management.ManagementClass "Root\default:StdRegProv"
c:\> $x.Methods | ft name

Name                                                 
----                                            
CreateKey                                                
DeleteKey                                                
EnumKey                                                  
EnumValues                                                
DeleteValue                                                
SetDWORDValue                                                
SetQWORDValue                                                
GetDWORDValue                                                
GetQWORDValue                                                  
SetStringValue                                                 
GetStringValue                                                 
SetMultiStringValue                                                
GetMultiStringValue                                                 
SetExpandedStringValue                                                
GetExpandedStringValue                                                 
SetBinaryValue                                                
GetBinaryValue                                                
CheckAccess                                                 
SetSecurityDescriptor           
GetSecurityDescriptor   

In effect you have four sets of methods:

  • Create/delete registry key (CreateKey, DeleteKey)
  • Enumerate a registry key or value entry (EnumKey, EnumValue)
  • Create, set or delete a value entry (Set<valuetype>Value, Get<valuetype>Value, DeleteValue)
  • Check security on a value/key (Check Access, SetAccessDescriptor, GetSDecurityDescriptor)

Each method is very easy to call, as you will have seen on my PshScripts blog. To manipulate the registry, you need to specfiy a registry Hive, a Registry Key, and where needed, a registry value. So to create a registry key, you could do this:

$HKEY_LOCAL_MACHINE = 2147483650
$Reg                = [WMIClass]"ROOT\DEFAULT:StdRegProv"
$Key                = "SOFTWARE\NewKey"
$Results            = $Reg.CreateKey($HKEY_LOCAL_MACHINE, $Key) 

In this case, you specify the  hive to create the key in by specifying a well known value, in case, 2147483650. The well known values are as follows:

HKEY_CLASSES_ROOT     2147483648
HKEY_CURRENT_USER     2147483649
HKEY_LOCAL_MACHINE    2147483650
HKEY_USERS            2147483651
HKEY_CURRENT_CONFIG   2147483653
HKEY_DYN_DATA         2147483654
With PowerShell, you first instantiate the class instance, which gets you an object on the local or remote machine. Then, you pass the static methods of htios class the values necessary. You always need to the specific well known numbers – in my example above, via a variable to the call the appropriate registry operation. The other paramaeters will depend on the specific call being made.
 
So to create a new MultiString regisgry value, below the key created earlier, you could do this:

$HKEY_LOCAL_MACHINE = 2147483650
$reg       = [WMIClass]"ROOT\DEFAULT:StdRegProv"
$Key       = "SOFTWARE\NewKey"
$ValueName = "Example MultiString Value"
$Values    = @("Thomas", "Susan", "Rebecca")
$Key       = "SOFTWARE\NewKey"
$reg.SetMultiStringValue($HKEY_LOCAL_MACHINE, $Key, $ValueName, $Values)

In this case, the code created a new MultiString value. There are no explicitly NEW methods on StdRegProv – you use a Set* method to either create a new value entry or change a value. With both getting and setting value entries, you use different methods depending on the specific value type you wish to manage (String, Multi—String, Binary, etc).  With removing a value, there’s only one method: DeleteValue.
 
One small thing to be careful of, DeleteKey, deletes the key specified and everything below it. So Deleting a key of “\” in most of the well known hives is probably not advisable.
 
All in all, it’s darn easy to use the StdRegProv class with PowerShell for all your registry manipulation needs.
Technorati Tags: ,,
 
 

Saturday, February 27, 2010

NITkon – Day Of PowerShell in Norway

For those in or around Norway next month (well Wednesday March 17th to be precise), NITKon, a Norwegian education conference for IT Pros in Norway, is holding Deep Dive PowerShell – a full day Of PowerShell content. I think this is the first conference to hold a full day just on PowerShell!

The contents of the day look pretty good too:

  • PowerShell Modules – Bruce Payette (superstar member of the development team and outstanding author)
  • Proxy Functions – Dmitry Sotnikov (fellow MVP and the brains behind PowerGui)
  • PowerShell and Wmi – ME!
  • PowerShell and .NET/COM objects – ME again
  • Advanced Features in PowerGui – Dmitry Sotnikov
  • PowerShell Advanced Techniques – Bruce Payette

I can’t wait for this event. I’m always keen to see Bruce and Dmitry – they are awesome speakers. I hope we will be able to post the slides once the event is complete.

Hope to see you there.

Technorati Tags: ,

Sunday, February 07, 2010

Solarwinds – Free WMI Monitor

I am slowly pulling together my upcoming PowerShell Master Class. One of the modules looks at WMI objects and I’ve been searching for as many cool tools etc as I can find. Thanks to a couple of tweets (Shay and Doug!), I found a pretty cool free tool from Solarwinds, called WMI Monitor. This is a free download that does a number of things, including:

  • monitors the performance on a Windows server
  • leverages pre-built and community generated application templates for monitoring virtually any application
  • enables you to modify or design your own application templates with the built-in WMI browser

This tool is free, but you do have to register. Also – it’s a 60mb download! But if you are doing WMI scripting with PowerShell, it might well be worth the download.

Technorati Tags: ,,

Friday, May 22, 2009

PowerShell and WMI Namespaces

Over on Tim Benninghoff blog – he has an interesting post:: PowerShell and WMI namespaces. With WMI, the classes and intances are organised under a hierarchal namespace starting at the appropriately named “root”.  Individual nodes can have children which can in turn have children and so on. To some degree, namespaces are just defined by a product team and there is little consistency across software products (such is life!). But where to start?

Despite what Tim says about using the GUI, MOW’s most excellent WMI Explorer script is one fantastic tool. Not only is it a really good browser, but as Tim notes, it’s written in PowerShell which is even more cool. I use this script in most of my training courses to add value!

His post then goes on to describe two methods of obtaining the namespaces within WMI. There are two small problems with his examples. In his first example he has a minor typo – this should read as follows:

gwmi -namespace "root" -class "__Namespace" | Select Name

In Tim’s post, he spelt the class with just a single underline (“_Namespace”) not two (“__Namespace”). WMI is sadly very picky!  Tim’s other method works fine and as he says produces the same output as his first (well once corrected!). On my system, this produces the following output:

PSH [C:\foo]: gwmi -namespace "root" -class "__Namespace" | Select Name

Name
----
subscription
DEFAULT
MicrosoftDfs
CIMV2
Cli
nap
MicrosoftIISv2
SECURITY
RSOP
MicrosoftDNS
WebAdministration
WMI
directory
Policy
virtualization
Hardware
ServiceModel
MSAPPS12
Microsoft
aspnet

The second point is that his two methods just produce a list of namespaces under the root. Since each node in the namespace can have children, his two methods do not list all the namespaces in which you can find classes. This, IMHO, is once case where the GUI is a better tool – visualising the hierarchy in a tree control is a whole lot easier than trying to do it from the command line. And you get the names spaces in alphabetical order (although you could do pipe the output above to Sort-Object easily enough). On my workstation I see a number of subsidiary namespaces below root as you can see here:

image

 

WMI Namespaces are a good thing to understand, since many of the classes you might want to access using Get-WMIObject (et al) rely on the –NameSpace paramater (and the appropriate namespace name!).

Technorati Tags: ,,,

Friday, April 24, 2009

Windows Management Infrastructure Blog

The WMI team are now blogging in the Windows Management Infrastructure Blog. A most useful blog for those wanting to understand WMI (and BITS, and WINRM) especially those coming to this from a PowerShell point of view. One interesting post examines the WMI story, pre Windows 7 (with lots of great links to more background). Another post looks at what is coming with WMI in Windows 7 (i.e. with PowerShell V2).

This blog is well written! And any blog that can mix PowerShell, reindeers, Jedis, ands and grasshoppers can’t be all bad!

Technorati Tags: ,,

Wednesday, April 15, 2009

Master-PowerShell by Dr. Tobias Weltner

As a PowerShell addict, I love sharing information about the product. I’ve just seen that Dr Tobias Weltner has finished off an e-book, entitled Master-PowerShell. This book is a free, 20-chapter work covering all aspects of PowerShell and is targeted at PowerShell Version 1. Thus, no details on Modules, remoting, etc, but nevertheless containing lots of useful information. I especially enjoyed reading Chapter 18 and learning more about PowerShell and WMI!

I recommend this book!

Master-PowerShell | With Dr. Tobias Weltner - PowerShell.com

Tuesday, February 24, 2009

OCS, WMI and PowerShell

This past week, I was teaching OCS Voice Ignite in Munich and a colleague (superstar Robin Edwards). During the week, we chatted about how to configure OCS’s Address Book service. This is a topic that comes up a lot in our OCS training, especially as the Address Book seems to be one of the key troubleshooting issues our delegates encounter.

As it turns out, you cannot do much with the GUI. There’s nothing there to enable you to do much more than view SOME of the settings. For example, by default, OCS ABS keeps 30 days worth of delta address books. If you login to Office Communicator, OC will download only the deltas since the last time you logged in, up to a certainly value – by default 30 days. This is a great feature for very large address books that don’t change a lot week to week.

The problem is, you can’t see this value in the GUI, nor can you set it. To view or change this, you need to use WMI in a direct way. Which leaves you three options: WBEMTest, VBS, or PowerShell. For most admins, WBEMTest is way too ugly and unfriendly and that probably is true for VBS. But PowerShell makes it very, very easy (assuming you know PowerShell of course).

The key settings for the Address Book Server are found in the WMI Class MSFT_SIPAddressBookSettings. This class is defined in MSDN at http://msdn.microsoft.com/en-us/library/bb632067.aspx.

This class has some useful properties, including:

DaysToKeep – specifies the number of days to keep the delta data files. The default is 30.

ExternalURL - An HTTPS URL that specifies the external location for address book file downloads

InternalURL - An HTTPS URL that specifies the internal location for address book file downloads.

MaxDeltaFileSizePercentage - The maximum percent of change for which a delta file is created. A delta file is not created if the percent of change is greater than this number. Multiply the value by 0.01 to derive the percentage. The minimum value for this property is 0 and the maximum value is 9999 (99.99%). The default value is 1250 (12.5%).

OutputLocation - Specifies the directory in which the files are stored.
PartitionOutputByOU - Controls whether data is partitioned by organization unit (OU).
RunTime - Specifies the service start time. The minimum value for this property is 0 and the maximum value is 2359. The default value is 130.

SynchronizeNow - When true, triggers the Address Book Server to perform a synchronization pass.

SynchronizePollingIntervalSecs - Specifies the number of seconds between checks for synchronization. The minimum value for this property is 5 and the maximum value is 9999.

UseNormalizationRules - Controls whether normalization is performed.

So much for what it does, now to how to do it with OCS R2. To get this class, using Standard Edition, you just use:

Get-WMIObject –Class MSFT_SipAddressbookSetting

However, using EE, it’s a bit more complex and you have to use a slightly different variation on the Get-WMIObject sytax, as follows:

PS C:\foo> gwmi -query "select * from MSFT_SipAddressBookSetting where backend='dc1'" -computer ocs-ee

Backend : dc1
DaysToKeep : 30
ExternalURL :
IgnoreGenericRules : False
InstanceID : {D265A402-BD08-4BCB-BEB3-CC7AFBD47C08}
InternalURL :
https://Cookham.gktrain.net/Abs/Int/Handler
MaxDeltaFileSizePercentage : 1250
OutputLocation : \\ocs-ee\absfiles
PartitionOutputByOU : False
RunTime : 130
SynchronizeNow : False
SynchronizePollingIntervalSecs : 300
UseNormalizationRules : True
WebServiceEnabled : True

So to make some changes, you could do something like this:

PS C:\foo> $abs = gwmi -query "select * from MSFT_SipAddressBookSetting where backend='dc1'" -computer ocs-ee
PS C:\foo> $abs.daystokeep = 45
PS C:\foo> $abs.runtime = 0230
PS C:\foo> $result = $abs.put()

PS C:\foo> gwmi -query "select * from MSFT_SipAddressBookSetting where backend='dc1'" -computer ocs-ee

Backend : dc1
DaysToKeep : 45
ExternalURL :
IgnoreGenericRules : False
InstanceID : {D265A402-BD08-4BCB-BEB3-CC7AFBD47C08}
InternalURL : https://Cookham.gktrain.net/Abs/Int/Handler
MaxDeltaFileSizePercentage : 1250
OutputLocation : \\ocs-ee\absfiles
PartitionOutputByOU : False
RunTime : 230
SynchronizeNow : False
SynchronizePollingIntervalSecs : 300
UseNormalizationRules : True
WebServiceEnabled : True

And finally – a bit tip of the hat to superstar Robin Edwards who showed me this class last week. Thanks Rob – you rock!

Technorati Tags: ,,

Monday, December 08, 2008

PowerShell WMI Based Audit Script

I’ve been writing about WMI and PowerShell of late – and notices this cool PowerShell Audit Script on Alan Renouf’s Virtu-Al’s blog. It’s not a particularly new post, but the result if pretty awesome. It produces a nice rich HTML file as output that looks a bit like this:

image

A great demonstration of what you can get from WMI plus what you can do with HTML in PowerShell

Technorati tags: ,

Saturday, December 06, 2008

Discovering WMI using Windows PowerShell

Around 2 1/2 years ago, I wrote a blog item entitled Discovering Networking with Monad and MSH where I looked at some aspects of WMI and how to discover more. Since then, I’ve published a few more articles on WMI.

The key thing for IT Pros to understand is that WMI is both a friend and other folks’ friend. What I meant by that is that WMI was built to be an interface. And for Microsoft, that means developer focused. WMI was the way for one application to surface management information and for other applications to leverage that information. This enables tools such as SCCM (aka SMS) to do such cool things.

But with PowerShell, the various classes of information are but a simple command away. The key is the GET-WmiObject cmdlet. This cmdlet enables you to retrieve any WMI class and access both its properties and methods and that means considerable power. PowerShell also provides WMI type accelerators, such as [WMI] that further simplify the use of WMI.

So how does an IT Pro get started. The first thing, I suppose is to understand how WMI is structured. To simplify, WMI is implemented on a host. On that host, there is a set of information that is organised with a hierarchical namespace which breaks up the information in a structured manner. In each Node of the WMI namespace, you’ll find a number of classes. Each class has a definition (what it should/can contain) and instances. Each instance of a class represents a real-world occurrence of that object. The class and hence the instance contains properties and methods. You can use the properties for reporting and can also update the values of these properties for any instance (and create and manipulate new instances). Instances (and the class) contain methods that you can call to get an instance to do something. The details of the namespaces, classes, properties and methods are described on MSDN.

With PowerShell, however the best place to start is with MOW’s most excellent WMI Explorer. This tool is incredibly cool. First, because it’s written all in PowerShell, but more importantly, because it’s the best browser I’ve seen. It’s a big PowerShell script – when you run it, you can open WMI on a system and browse the namespaces. In each namespace node you can look at the classes in that node. And for each class, you can simply see both the existing instances as well as the definition of that class. Here’s a screen shot of this tool running on one of my workstations:

image

As an IT Pro, you should download WMI Explorer and explore. I’ll be posting more on WMI and PowerShell coming up.

Technorati Tags: ,,

Monday, February 04, 2008

PowerShell's [WMI] Type Accelerator

In a recent blog post, I introduced PowerShell's WMI related type accelerators. In this post, I'll look at the [WMI] accelerator in more detail. As I explained earlier, the [WMI] type accelerator helps you to get directly to a particular WMI object. You provide a string containing the path to a particular WMI object and the [WMI]  adapter returns the WMI object (or not if it does not exist). This approach is a little easier than using Get-WMIObject in those cases when you actually know the details of which occurrence you want.

To illustrate this TA, let's look at a WMI Class, Win32_Share. We can find all the shares on a system like this:

PSH [D:\foo]: gwmi win32_share | ft -auto

Name   Path       Description
----   ----       -----------
E$     E:\        Default share
IPC$              Remote IPC
D$     D:\        Default share
ADMIN$ C:\WINDOWS Remote Admin
foo    d:\foo
C$     C:\        Default share

This is fine if you want to just see the shares.  But if you want to access a particular share's methods or properties you need to do a bit more  work. One simple way you can  get access to the Admin$ share is like this:

PSH [D:\foo]: $admin = gwmi win32_share | where {$_.name -eq "Admin$"}

This approach works, but it's a bit ugly and can take some time if there are a lot of shares on a system. And here's where the [WMI] TA works well as follows:

$admin2 = [wmi]"\\dc1\root\cimv2:win32_share.name='admin$'"

This is much easier to write, assuming you know how to construct the path string. A simple way to determine how to construct the path for this TA is to look at the __Path property on the actual object:

PSH [D:\foo]: $admin = gwmi win32_share | where {$_.name -eq "Admin$"}
PSH [D:\foo]: $admin.__Path
\\dc1\root\cimv2:Win32_Share.Name="ADMIN$"

To convert this path for use with [WMI], you need first to replace the double quotes to single quotes, then enclose the resulting string in double quotes prepended with [WMI].  One nice feature of this approach is that the returned object is an object, not a collection/array, which makes it easier to use.

When I was creating this blog post, I wondered if it was possible to create a WMI path using other properties. However this does not appear to work:

PSH [D:\foo]: $admin3 = [wmi]"\root\cimv2:win32_share.description='Remote Admin'"
Cannot convert value "\root\cimv2:win32_share.description='Remote Admin'" to type "System.Management.ManagementObject".
Error: "Invalid object path "
At line:1 char:11
+ $admin3 = [wmi] <<<< "\root\cimv2:win32_share.description='Remote Admin'"
PSH [D:\foo]: $admin3 = [wmi]"\root\cimv2:win32_share.path='c:\windows'"
Cannot convert value "\root\cimv2:win32_share.path='c:\windows'" to type "System.Management.ManagementObject". Error: "
Invalid object path "
At line:1 char:11
+ $admin3 = [wmi] <<<< "\root\cimv2:win32_share.path='c:\windows'"

There are two different formats you can se for the WMI path - with and without a machine name as follows:

$admin4 = [wmi]"\\dc1\root\cimv2:win32_share.name='admin$'"
$admin5 = [wmi]"root\cimv2:win32_share.name='admin$'"

The first format includes a machine name (\\dc1) while the second doesn't. The second format only works on the local machine whereas the first  can work across a network. There's only one small issue (feature?) of the first format which is that you can not provide credentials. Thus if you are logged onto your local machine with your normal userid/password, that set of credentials is used to access WMI. If those credentials do not allow you to access the remote server, then there's no way to provide credentials that would work.

I hope this is a clear explanation - let me know if  you'd like more details.

Wednesday, January 30, 2008

WMI, PowerShell and PowerShell's WMI Type Accelerators

I've been playing with PowerShell's WMI interface as part of some writing work I'm doing. As I see it, PowerShell lacks built-in cmdlets to do everything. However that really is not a problem since a lot of thing can be pretty easily achieved using a few lines of PowerShell! 

PowerShell introduces the concept of type accelerators. These look like normal .NET types (type name specified inside square brackets), but they are managed by PowerShell itself. Type accelerators are just shortcuts to existing underlying functionality.

There are three WMI related type accelerators in PowerShell V1. If you are using  WMI with PowerShell, you really should know these three:

  • [WMI] - this TA helps you to get directly to a particular WMI object. You provide a string containing a detailed path to a particular WMI object and the TA returns the object. This is a little easier than using Get-WMIObject in those cases when you actually know the details of which occurrence you want.
  • [WMICLASS] - this TA gets you to a class definition. This then enables you to access WMI Class static methods. The Get-WMIObject enables you to get to instances, but to create new instances you need access to the static methods of the class.
  • [WMISEARCHER] - this TA helps you in terms of querying. When creating a WMISEARCHER, you specify a WQL query (e.g. Select * FROM Win32_Process WHERE Handlecount > 1000). You can use the searcher to execute that query and return results. This is a little easer for some times of administration.

WMI Type Accelerators are not well defined or well documented either on MSDN or inside the product itself. I hope my attempts at providing this information are useful - let me know what I'm missing and I'll try to add it. Over the coming week or so, I'll be blogging about each type accelerator in more detail. The posts also contain some simple sample code that demonstrates these cool features.

Did I mention - PowerShell rocks!!!

Technorati tags: , ,

Saturday, June 16, 2007

WMI Win32_Volume Class using PowerShell

I've been playing around this weekend with PowerShell and the Win32_Volume WMI class and have written some PowerShell scripts to exploit this class.

To get the volumes on a system is trivial:

$volumes = Get-WMIObject Win32_Volume

This returns an array of volume objects which you can iterate through and display. To display the whole collection, or to just see the first volume, you could do this:

$volumes
$volumes[0]

See here for a simple script that obtain the volumes on a system and then displays their information. Then look at this script to run a chkdsk on the system.

You can also use a method to determine how badly fragmented a volume is, and another to run a defrag pass on a volume. Look here for a script to display a defrag analysis of the C:\ and here to actually defrag the disk.

 

[Later Update]

The Win32_Volume WMI class is not available on all versions of Windows - I ran the scripts on a Longhorn B3 server.

 

Technorati tags: , ,