Continuing to take advantage of using WMI to get data from workstations, another project recently came up to get an inventory of printers installed across my organization. It ended up being a pretty easy task using WMI through a startup script but the results could be tailored more by being selective about the results. Combined with formatting the output as a csv and later merging the output into a single file, the script in all its simplicity is essentially a single line. A few lines of logic around it smooths out the process to be more efficient than running every startup.
The command comes down to using WMIC.exe to query the Printer class. You can get a lot of attributes about your printer this way. The wheels in my head are already turning to include this in a standard backup script as an excellent source of information without the heavy-handedness of PrintMigrator.
The script in its simple form looks like this:
wmic.exe PRINTER GetName, PortName, DriverName
Adding a little complexity to it like a SQL statement (SELECT-FROM-WHERE), we can add a Where conditional to limit our data to only return what we want. For example, return only printers with the term HP in the DriverName.
wmic.exe PRINTER where "DriverName like '%HP%'" Get Name, PortName, DriverName, Default, ShareName
To continue to tailor the data, you can logically combine conditions to get exactly what you want.
wmic printer where "DriverName like '%HP%' OR DriverName like '%Microsoft%'" Get Name, PortName, DriverName
You can also invert the statement to get everything but what matches the query by using a NOT statement. Try this out:
wmic printer where "not DriverName like '%HP%'" Get Name, PortName, DriverName
Using the wildcards in a batch or command script is very similar. The only difference to remember is using two percent signs to escape the wildcard in the script so it gets passed through instead of being executed. You can see the full script that makes use of this below.
@ECHO OFF REM Printer query script REM Jason Hamilton, June 2012 REM Check if file exists, if so, skip IF EXIST \servershare%COMPUTERNAME%.txt GOTO END
WMIC.exe /output:\servershare%COMPUTERNAME%.txt PRINTER where "DriverName like '%%HP%%'" GET Name, PortName, DriverName /format:csv
If you get a result that states invalid query or just returns ‘node,’ it may just mean that the computer doesn’t have any information that meets your conditions.
Of course, you can use this on other WMIC classes like Services, BIOS, and ComputerSystem to create a query that gets just the information you want.