Labels

Thursday, July 24, 2008

WMIC Custom Alias and Format

This post describes my first attempt at creating a WMIC alias, which provides an easy way of allowing people to run complex queries with a single alias.

Note that while creating new WMIC aliases provides a very flexible and transportable solution, another very useful part of WMIC discussed here is the use of the 'format' command to format the output in one of many formats - CSV, XML, HTML tables - or passed through any custom XSL.

The examples here provide an alias and output of printer jobs from a cluster node, using the perfdata information, which combined with HTML table output, provides a repeatable method of displaying print spooler information on a 2003 cluster node.

As a summary, this post describes using WMIC to:

  • Use the format command to modify output, using either an alias or a path/get command
  • Create, compile and run a custom alias using WMIC
  • Modify one of the builtin XSL files to allow sorting by ascending/descending

The Format option

The following commands provide different examples of formatting output as CSV from a path/get command, as well as various combinations of using the custom alias created below.

Use WMIC to get instances of a class and format the output as CSV
wmic path win32_process get name,commandline /format:csv

Use WMIC aliases to format the output in CSV or XML
wmic process list /format:xml
wmic process list /format:csv

Use WMIC aliases to format the output in HTML TABLE, MOFCSV or XML
wmic process list /format:htable
wmic process list /format:HMOF

Use WMIC aliases to sort the output in HTML
wmic process list /format:htable:"sortby=Name" > test.html

Use WMIC aliases to filter and sort the output in CSV
wmic process get name /format:csv:"datatype=text":"sortby=Name"

Use WMIC remotely aliases to retrieve command-line process arugments
wmic /node:"%server%" process get name,CommandLine /format:csv:"sortby=Name"

Use WMIC wmic aliases to sort the result set by number
wmic Logon get /Format:htable:"datatype=number":"sortby=LogonType"

Use a custom WMIC alias to report printer info from a cluster node in CSV
wmic /node:"%server%" spoolerjobs list /format:table

Use a custom WMIC alias to report sorted HTML printer info from a cluster node
wmic /node:"%server%" spoolerjobs list /format:htable:"datatype=number":"sortby=TotalJobsPrinted"

Use a custom WMIC alias to report a brief summary of printer statistics
wmic /node:"%server%" spoolerjobs list brief /format:htable:"datatype=number":"sortby=TotalJobsPrinted"

Use a custom WMIC alias and xsl to sort print jobs output descending HTML table
wmic /node:"%server%" spoolerjobs list brief /format:"htabledesc-sortby.xsl":"datatype=number":"orderby=descending":"sortby=TotalJobsPrinted" > test.html

Query a user from AD using WMI
wmic /node:"%DC%" /namespace:\\root\directory\LDAP path ds_user where "ds_cn='%username%'" GET ds_displayName,DS_UserPrincipalName,ds_cn,ds_name,ds_whenCreated


Create, compile and run a custom alias using WMIC

The following steps were taken to created and compile the MOF file:

  1. Use the CIM Studio, root\cli namespace
  2. Select the MSFT_CliAlias Class
  3. Double-click the 'MOF Generator' button (top-right, next to 'MOF Compiler' which is next to the help icons).
  4. Select at least one instance of the class to export as well. The 'Startup' alias is relatively simple and was used in this example
  5. Choose a filename and path
  6. Remove the class definition from the MOF
  7. Modify the instance definition -
    1. Create/modify MSFT_CliProperty properties to set the derivation, description and name as appropriate for the data you are retrieving
    2. Add qualifiers to the objects as appropriate, providing greater integrity of the dataset
    3. Change the FriendlyName to be the new alias name, and the target WMI query
    4. Use the PWhere attribute to specify an optional where query clause with the value specified at the command prompt
  8. Use mofcomp -check to validate the MOF
  9. Use mofcomp to compile into the repository

To customise the XSL to add the ability to sort by ascending or descending in the htable output:

  1. copy c:\WINDOWS\system32\wbem\htable-sortby.xsl c:\WINDOWS\system32\wbem\htabledesc-sortby.xsl
  2. Add parameter: <xsl:param name="orderby" select="'ascending'"/>
  3. In the XSL:Sort element, add: order="{$orderby}"

The MOF file:



//**************************************************************************
//* File: ClusterPrintJobs.mof
//**************************************************************************

// References:
// 
// Win32_PerfFormattedData_Spooler_PrintQueue Class
// http://msdn.microsoft.com/en-us/library/aa394288(VS.85).aspx
//
// Creating and editing formats in WMIC
// http://technet2.microsoft.com/windowsserver/en/library/32757e77-daa3-461a-8576-10242178de581033.mspx?mfr=true
//
// Creating and editing aliases
// http://technet2.microsoft.com/windowsserver/en/library/fd84c63a-d94d-4adc-99c2-8f71d7494c5d1033.mspx

// Author:  Wayne Martin
// Date:    22/07/2008
//
// 
// Example uses:
// Use a custom WMIC alias to report printer info from a cluster node in CSV:
//   wmic /node:"b%server%" spoolerjobs list /format:table
//
// Use a custom WMIC alias to report sorted HTML printer info from a cluster node:
//   wmic /node:"%server%" spoolerjobs list /format:htable:"datatype=number":"sortby=TotalJobsPrinted"
//
// Use a custom WMIC alias to report a brief summary of printer statistics
//   wmic /node:"%server%" spoolerjobs list brief /format:htable:"datatype=number":"sortby=TotalJobsPrinted"
//
// Use a custom WMIC alias and xsl to sort print jobs output descending HTML table
//   wmic /node:"%server%" spoolerjobs list brief /format:"htabledesc-sortby.xsl":"datatype=number":"orderby=descending":"sortby=TotalJobsPrinted" > test.html 


//**************************************************************************
//* This MOF was generated from the "\\.\ROOT\cli"
//* namespace on machine "-".
//* To compile this MOF on another machine you should edit this pragma.
//**************************************************************************
#pragma namespace("\\\\.\\ROOT\\cli")


//**************************************************************************
//* Instances of: MSFT_CliAlias
//**************************************************************************
instance of MSFT_CliAlias
{
 Connection = 
 instance of MSFT_CliConnection
 {
  Locale = "ms_409";
  NameSpace = "ROOT\\CIMV2";
  Server = ".";
 };
 Description = "List print jobs for each printer on the specified node, and spooler totals.";
 Formats = {
  instance of MSFT_CliFormat
  {
   Name = "SYSTEM";
   Properties = {
    instance of MSFT_CliProperty
    {
     Derivation = "__CLASS";
     Name = "__CLASS";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__DERIVATION";
     Name = "__DERIVATION";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__DYNASTY";
     Name = "__DYNASTY";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__GENUS";
     Name = "__GENUS";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__NAMESPACE";
     Name = "__NAMESPACE";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__PATH";
     Name = "__PATH";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__PROPERTY_COUNT";
     Name = "__PROPERTY_COUNT";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__RELPATH";
     Name = "__RELPATH";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__SERVER";
     Name = "__SERVER";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "__SUPERCLASS";
     Name = "__SUPERCLASS";
    }
   };
  }, 
  instance of MSFT_CliFormat
  {
   Name = "INSTANCE";
   Properties = {
    instance of MSFT_CliProperty
    {
     Derivation = "Name";
     Description = "the print queue. ";
     Name = "Name";
     Qualifiers = {
      instance of MSFT_CliQualifier
      {
       Name = "MaxLen";
       QualifierValue = {"64"};
      }
     };
    }
   };
  }, 
  instance of MSFT_CliFormat
  {
   Format = "LIST";
   Name = "FULL";
   Properties = {
    instance of MSFT_CliProperty
    {
     Derivation = "Name";
     Description = "Name of the print queue.";
     Name = "Name";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "Jobs";
     Description = "Current number of jobs in a print queue.";
     Name = "Jobs";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "TotalJobsPrinted";
      Description = "Total number of jobs printed on a print queue after the last restart.";
      Name = "TotalJobsPrinted";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "TotalPagesPrinted";
     Description = "Total number of pages printed through GDI on a print queue after the last restart.";
     Name = "TotalPagesPrinted";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "MaxJobsSpooling";
     Description = "Maximum number of spooling jobs in a print queue after the last restart.";
     Name = "MaxJobsSpooling";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "JobErrors";
     Description = "Total number of job errors in a print queue after the last restart.";
     Name = "JobErrors";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "OutOfPaperErrors";
     Description = "Total number of out-of-paper errors in a print queue after the last restart.";
     Name = "OutOfPaperErrors";
     Qualifiers = {
      instance of MSFT_CliQualifier
      {
       Name = "CookingType";
       QualifierValue = {"PERF_COUNTER_RAWCOUNT"};
      },
      instance of MSFT_CliQualifier
      {
       Name = "Counter";
       QualifierValue = {"OutofPaperErrors"};
      },
      instance of MSFT_CliQualifier
      {
       Name = "PerfTimeStamp";
       QualifierValue = {"Timestamp_PerfTime"};
      },
      instance of MSFT_CliQualifier
      {
       Name = "PerfTimeFreq";
       QualifierValue = {"Frequency_PerfTime"};
      }
     };
    }
   };
  }, 
  instance of MSFT_CliFormat
  {
   Format = "TABLE";
   Name = "BRIEF";
   Properties = {
    instance of MSFT_CliProperty
    {
     Derivation = "Name";
     Description = "Name of the print queue.";
     Name = "Name";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "TotalJobsPrinted";
     Description = "Total number of jobs printed on a print queue after the last restart.";
     Name = "TotalJobsPrinted";
    }, 
    instance of MSFT_CliProperty
    {
     Derivation = "TotalPagesPrinted";
     Description = "Total number of pages printed through GDI on a print queue after the last restart.";
     Name = "TotalPagesPrinted";
    }
   };
  }
 };
 FriendlyName = "SpoolerJobs";
 //PWhere = "where Caption='#'";
 Target = "Select Name,Jobs,TotalJobsPrinted,TotalPagesPrinted,MaxJobsSpooling,JobErrors,OutOfPaperErrors from Win32_PerfFormattedData_Spooler_PrintQueue";
};

//* EOF ClusterPrintJobs.mof


References:

WMI Adminsitrative Tools (contains CIM Studio):
http://www.microsoft.com/downloads/details.aspx?FamilyID=6430f853-1120-48db-8cc5-f2abdc3ed314

Wayne's World of IT (WWoIT), Copyright 2008 Wayne Martin.

1 comment:

jv said...

Need to declare "UnicOde" on NetFileEnum function so strings are passed correctly.

Declare Unicode Function NetFileEnum Lib "netapi32.dll" ( _
ByVal servername As String, _
ByVal basepath As String, _
ByVal username As String, _
ByVal level As Integer, _
ByRef bufptr As IntPtr, _
ByVal prefmaxlen As Integer, _
ByRef entriesread As Integer, _
ByRef totalentries As Integer, _
ByVal resume_handle As IntPtr) As Integer

Also add structure packing attributes to FIL_INFO_# structure.

<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto, Pack:=4)> _


All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 13 years, and I know just about enough to realise that I don’t know very much.