Pliant AllianceSoftware development notes & tools

Using Windows Management Instrumentation for Scripts

Windows Management Instrumentation, usually shortened to WMI, gives scripts a structured way to inspect and administer Windows computers. Instead of opening Control Panel pages or reading scattered registry values, a script can ask the operating system for information about services, disks, processes, users, hardware and installed software.

WMI is best understood as an information layer rather than a single utility. It presents operating-system data through classes, properties and methods. A script can query a class such as Win32_OperatingSystem, filter the returned objects, and then decide whether to report a result, repair a setting or raise an alert.

This approach was especially useful when a Windows network contained machines with different hardware and software combinations. An administrator could run the same inventory routine across desktops in a Sydney office, laptops used between Melbourne and regional sites, and servers located elsewhere, without relying on each computer having an identical configuration.

The technology rewards careful scripting. Queries that appear harmless can generate considerable network traffic, while methods that alter services or accounts require appropriate privileges. A useful WMI script is therefore specific, logged and conservative about making changes.

Understanding the WMI model

WMI organises management information into namespaces and classes. The default namespace for many everyday Windows tasks is root\cimv2. Within it, classes describe particular kinds of resources. Win32_LogicalDisk represents drives, Win32_Service represents services, and Win32_Process represents running processes. Each class exposes properties, such as a disk’s free space, and sometimes methods, such as stopping a service.

The objects returned by WMI are not always simple snapshots. Some are associated with providers that obtain data from the operating system when queried. Others expose methods that ask Windows to perform an operation. This distinction matters: reading a process list is generally low risk, whereas invoking a method to terminate a process can interrupt a user’s work.

A query uses a language called WMI Query Language, or WQL. It resembles a restricted form of SQL:

SELECT Name, State, StartMode
FROM Win32_Service
WHERE State = 'Running'

WQL is designed for management data rather than arbitrary database work. It supports common filtering and selection, but scripts should avoid retrieving every property from every object when only a few values are needed. Selecting Name, State, StartMode is clearer and usually lighter than using SELECT *.

Classes can also be related. For instance, Win32_LogicalDisk can describe fixed disks, removable media and network drives, with the DriveType property helping a script distinguish them. Documentation for each class is essential because property availability varies between Windows versions, hardware configurations and installed providers.

Querying local computers with PowerShell

PowerShell provides a natural interface to WMI and its newer Common Information Model, or CIM, commands. On current Windows systems, Get-CimInstance is generally preferred:

Get-CimInstance -ClassName Win32_OperatingSystem |
    Select-Object CSName, Caption, Version, LastBootUpTime

This command returns selected details about the operating system and the computer name. WMI dates are converted into useful PowerShell date values by the CIM layer, making it easier to calculate uptime or compare patching intervals.

A disk-space check can be concise while still being readable:

Get-CimInstance Win32_LogicalDisk -Filter "DriveType = 3" |
    Select-Object DeviceID,
        @{Name='FreeGB'; Expression={[math]::Round($_.FreeSpace / 1GB, 2)}},
        @{Name='SizeGB'; Expression={[math]::Round($_.Size / 1GB, 2)}}

The filter is sent to the provider rather than applied only after all objects have been returned. This becomes valuable when the same script runs across a large group of computers. A local query is usually straightforward, but a script should still handle missing values: a removable or unusual volume may not report a normal size, and a machine may have no fixed disk matching the filter.

Older Windows environments commonly used Get-WmiObject, and legacy scripts may still contain it:

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType = 3"

The command remains useful when maintaining historical systems, but new scripts should favour CIM cmdlets where the operating-system version permits them. The object model is similar, so migrating a simple read-only query is usually uncomplicated.

Running scripts against remote machines

Remote WMI administration depends on more than a correct query. The account running the script must have suitable rights, the target computer must permit remote management, and firewalls must allow the required traffic. Traditional WMI remoting commonly uses DCOM, which can require several firewall and authentication settings. CIM sessions can use WS-Management, the same general transport used by PowerShell remoting.

A remote query with a CIM session might look like this:

$session = New-CimSession -ComputerName 'PC-ACCOUNTS-07'

Get-CimInstance -CimSession $session `
    -ClassName Win32_OperatingSystem |
    Select-Object CSName, Caption, Version

Remove-CimSession $session

For several machines, create sessions deliberately and close them when the work is complete:

$names = 'PC-ACCOUNTS-07', 'PC-RECEPTION-02', 'PC-WAREHOUSE-11'

foreach ($name in $names) {
    try {
        Get-CimInstance -ComputerName $name `
            -ClassName Win32_LogicalDisk `
            -Filter "DriveType = 3" `
            -ErrorAction Stop |
            Select-Object @{Name='Computer'; Expression={$name}},
                DeviceID, FreeSpace
    }
    catch {
        Write-Warning "$name could not be queried: $($_.Exception.Message)"
    }
}

A script should not assume that a failed connection means a broken computer. The machine may be asleep, disconnected from a virtual private network, using a different firewall profile or subject to a name-resolution problem. In Australia, an organisation with offices in Brisbane, Perth and Adelaide may also have links with different latency and maintenance windows. Logging the computer name, time and exact error is more useful than silently skipping the result.

Remote administration deserves particular care where personal information is involved. A process list, logged-on user name or software inventory can identify individuals and their work habits. Organisations operating under Australia’s Privacy Act 1988 should limit collection to a legitimate administrative purpose, protect exported reports and define how long the records are retained.

Inspecting and changing services safely

WMI is useful for checking whether important services are present and running. A monitoring script can examine the Windows Update service, an antivirus agent or a line-of-business service:

$service = Get-CimInstance Win32_Service `
    -Filter "Name = 'wuauserv'"

[pscustomobject]@{
    Computer = $service.SystemName
    Name     = $service.Name
    State    = $service.State
    StartMode = $service.StartMode
}

The result can be written to CSV, displayed in a dashboard or compared with a baseline. A service that is stopped is not always an incident: some services are demand-started, and a maintenance task may have stopped another temporarily. The script should know the expected state before it attempts a repair.

Methods exposed by WMI can start, stop, pause or change services. A controlled example is:

$service = Get-CimInstance Win32_Service `
    -Filter "Name = 'wuauserv'"

if ($service -and $service.State -eq 'Stopped') {
    Invoke-CimMethod -InputObject $service -MethodName StartService
}

Changing configuration should be separated from diagnosis whenever possible. A report-only mode allows an administrator to confirm which machines would be affected. It is also sensible to restrict changes to an approved list, record the operator and retain the method’s return code. WMI methods often return a numeric status rather than throwing a clear exception, so the script must interpret that result.

The same caution applies to process management. Win32_Process can call Terminate, yet killing a process may lose unsaved documents or interrupt a database task. Service recovery is safer when the script checks the service name, startup configuration and dependent services first.

Using VBScript in older Windows environments

WMI became widely used in Windows administration before PowerShell was common. VBScript remains relevant when supporting older computers, login scripts or management systems that expect a .vbs file. The following example reports the operating-system caption and version:

Set locator = CreateObject("WbemScripting.SWbemLocator")
Set service = locator.ConnectServer(".", "root\cimv2")

Set items = service.ExecQuery( _
    "SELECT Caption, Version FROM Win32_OperatingSystem")

For Each item In items
    WScript.Echo item.Caption & " " & item.Version
Next

The first argument to ConnectServer is the computer name. Replacing "." with a remote host name makes the target explicit, although permissions and firewall requirements still apply. A production script should include error handling around the connection and query, because an unhandled WMI error can terminate a batch of inventory work.

VBScript can also inspect disk space:

Set disks = service.ExecQuery( _
    "SELECT DeviceID, FreeSpace, Size " & _
    "FROM Win32_LogicalDisk WHERE DriveType = 3")

For Each disk In disks
    WScript.Echo disk.DeviceID & " free bytes: " & disk.FreeSpace
Next

The values returned by WMI may be empty or unsuitable for arithmetic if a provider has no data. Scripts should test for Null before performing calculations. Converting byte counts to gigabytes also requires care because storage vendors and operating systems may use different conventions.

Older administrative environments often mixed VBScript, batch files and scheduled tasks. That arrangement can be dependable when each script has a narrow responsibility, but credentials should never be embedded in plain text. Use a managed service account or an appropriately delegated user, and protect script files on shared drives. This is particularly relevant for small Australian businesses that may rely on a single file server and a modest outsourced IT arrangement.

Building reliable inventory and maintenance scripts

A useful WMI script begins with a defined question. “Collect everything” produces large, difficult-to-protect reports. A better request might be “find Windows computers with less than 15 per cent free space and an outdated endpoint service”. The script can then query only the classes and properties needed for that decision.

Inventory output should include a timestamp, computer name, query purpose and an indication of success or failure. CSV is convenient for small jobs, while structured formats such as JSON preserve data types more effectively. Avoid storing sensitive fields without a reason. A software inventory can reveal licensing information, and user or process data may have privacy implications under internal policy and Australian law.

Testing should cover unavailable computers, empty results, access-denied responses and unexpected property values. Run a read-only version against a pilot group before using it across production machines. Check the effect on older Windows releases and confirm that the query does not depend on a class supplied only by a particular vendor’s hardware management software.

Operational context also matters. Australia’s Essential Eight guidance places emphasis on application control, patching, restricting administrative privileges and monitoring. WMI can support those activities by reporting operating-system versions, service states and selected configuration details, but it does not replace a patch-management system or an endpoint security platform. A script that collects evidence should complement, rather than bypass, established controls.

Time handling deserves attention in scheduled jobs. A maintenance task running across Sydney, Darwin and Perth can produce confusing reports if local time is assumed everywhere. Store timestamps consistently, preferably in UTC, and convert them for display. Daylight saving changes in New South Wales, Victoria and South Australia do not apply in the same way to Queensland, the Northern Territory or Western Australia.

The strongest WMI scripts are modest in scope. They ask precise questions, request limited data, authenticate through approved mechanisms and record what happened. With those habits, Windows management classes become a practical foundation for inventory, health checks and carefully controlled administration across both old and modern estates.