Reading Printer Properties (Part 2)

by Aug 5, 2021

Categories

Tags

Administration agent-based monitoring Agentless Monitoring alert responses alert thresholds alerting Alerts Amazon Aurora Amazon EC2 Amazon RDS Amazon RDS / Aurora Amazon RDS for SQL Server Amazon Redshift Amazon S3 Amazon Web Services (AWS) Analytics application monitoring Aqua Data Studio automation availability Azure Azure SQL Database azure sql managed instance Azure VM backup Backup and recovery backup and restore backup compression backup status Backup Strategy backups big data Blocking bug fixes business architecture business data objects business intelligence business process modeling business process models capacity planning change management cloud cloud database cloud database monitoring cloud infrastructure cloud migration cloud providers Cloud Readiness Cloud Services cloud storage cloud virtual machine cloud VM clusters code completion collaboration compliance compliance audit compliance audits compliance manager compliance reporting conference configuration connect to database cpu Cross Platform custom counters Custom Views customer survey customer testimonials Dark Theme dashboards data analysis Data Analytics data architect data architecture data breaches Data Collector data governance data lakes data lineage data management data model data modeler data modeling data models data privacy data protection data security data security measures data sources data visualization data warehouse database database administration database administrator database automation database backup database backups database capacity database changes database community database connection database design database developer database developers database development database diversity Database Engine Tuning Advisor database fragmentation database GUI database IDE database indexes database inventory management database locks database management database migration database monitoring database navigation database optimization database performance Database Permissions database platforms database profiling database queries database recovery database replication database restore database schema database security database support database synchronization database tools database transactions database tuning database-as-a-service databases DB Change Manager DB Optimizer DB PowerStudio DB2 DBA DBaaS DBArtisan dBase DBMS DDL Debugging defragmentation Demo diagnostic manager diagnostics dimensional modeling disaster recovery Download drills embedded database Encryption End-user Experience entity-relationship model ER/Studio ER/Studio Data Architect ER/Studio Enterprise Team Edition events execution plans free tools galera cluster GDPR Getting Started Git GitHub Google Cloud Hadoop Healthcare high availability HIPAA Hive hybrid clouds Hyper-V IDERA IDERA ACE Index Analyzer index optimization infrastructure as a service (IaaS) infrastructure monitoring installation Integrated Development Environment interbase Inventory Manager IT infrastructure Java JD Edwards JSON licensing load test load testing logical data model macOS macros managed cloud database managed cloud databases MariaDB memory memorystorage memoryusage metadata metric baselines metric thresholds Microsoft Azure Microsoft Azure SQL Database Microsoft PowerShell Microsoft SQL Server Microsoft Windows MongoDB monitoring Monitoring Tools Monyog multiple platforms MySQL news newsletter NoSQL Notifications odbc optimization Oracle PeopleSoft performance Performance Dashboards performance metrics performance monitoring performance schema performance tuning personally identifiable information physical data model Platform platform as a service (PaaS) PostgreSQL Precise Precise for Databases Precise for Oracle Precise for SQL Server Precise Management Database (PMDB) product updates Project Migration public clouds Query Analyzer query builder query monitor query optimization query performance Query Store query tool query tuning query-level waits Rapid SQL rdbms real time monitoring Real User Monitoring recovery regulations relational databases Releases Reporting Reports repository Restore reverse engineering Roadmap sample SAP Scalability Security Policy Security Practices server monitoring Server performance server-level waits Service Level Agreement SkySQL slow query SNMP snowflake source control SQL SQL Admin Toolset SQL CM SQL code SQL coding SQL Compliance Manager SQL Defrag Manager sql development SQL Diagnostic Manager SQL Diagnostic Manager for MySQL SQL Diagnostic Manager for SQL Server SQL Diagnostic Manager Pro SQL DM SQL Doctor SQL Enterprise Job Manager SQl IM SQL Inventory Manager SQL Management Suite SQL Monitoring SQL Performance SQL Quality SQL query SQL Query Tuner SQL Safe Backup SQL script SQL Secure SQL Security Suite SQL Server sql server alert SQL Server Migration SQL Server Performance SQL Server Recommendations SQL Server Security SQL statement history SQL tuning SQL Virtual Database sqlmemory sqlserver SQLyog Storage Storage Performance structured data Subversion Support tempdb tempdb data temporal data Tips and Tricks troubleshooting universal data models universal mapping unstructured data Uptime Infrastructure Monitor user experience user permissions Virtual Machine (VM) web services webinar What-if analysis WindowsPowerShell

In the previous tip we looked at Get-PrinterProperty which is part of the PrintManagement module and available on Windows operating systems.

In this tip, let’s check out how you can actually use the printer values in your own scripts, and how storing them in a hash table makes accessing printer properties much easier compared to working with simple arrays.

Important: the actual printer properties and their names depend on your printer model and printer driver. The property names used in the examples above may be different for your printer(s).

When you store the result returned by Get-PrinterProperty in a variable, the variable contains a simple array, and it is your job to identify the array element with the property you are after. Here is an example:

 
PS> $info = Get-PrinterProperty -PrinterName 'S/W Laser HP'

# return result is an array
PS> $info -is [Array]
True

# array elements can only be accessed via numeric index
PS> $info.Count
64

# the number of returned properties depends on the printer model
# the index of given properties may change so accessing a property by
# index works but can be unreliable:
PS> $info[0]

ComputerName         PrinterName          PropertyName         Type       Value
------------         -----------          ------------         ----       -----
                     S/W Laser HP         Config:AccessoryO... String     500Stapler


# the actual property value is stored in the property “Value”
PS> $info[0].Value
500Stapler

# using comparison operators, you can convert string content to Boolean
# for example to check whether a printer has a certain feature installed
PS> $info[2]

ComputerName         PrinterName          PropertyName         Type       Value
------------         -----------          ------------         ----       -----   
                     S/W Laser HP         Config:AutoConfig... String     NotInstalled

PS> $info[2].Value 
NotInstalled

PS> $info[2].Value -eq 'NotInstalled'
True 

A much safer way is to store the result in a hash table and use the original property names as keys. It is not well known that Group-Object can automatically create hash tables for you. Just tell Group-Object what the name of the property is that you want to use for grouping, and ask to get back a hash table and use strings as hash table keys:

 
$info = Get-PrinterProperty -PrinterName 'S/W Laser HP' | Group-Object -Property PropertyName -AsHashTable -AsString   

This time, $info contains a hash table, and if you use a PowerShell editor with IntelliSense like ISE or VSCode, once you add a dot to the variable name, you get rich IntelliSense showing available property names. In the console, you can press TAB to use autocompletion.

Since the IntelliSense menu and TAB completion also contains a few hash table-related properties and methods, you may have to scroll down a bit or press TAB a few times respectively.

To query the value of a printer property, once you picked a property name, you need to add quotes around the property name because typically, printer property names contain special characters like colons:

 
# hash table keys need to be quoted
PS> $info.Config:AccessoryOutputBins
At line:1 char:13
+ $info.Config:AccessoryOutputBins
+             ~~~~~~~~~~~~~~~~~~~~
Unexpected token ':AccessoryOutputBins' in expression or statement.
        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : UnexpectedToken
  
  
# once you add quotes, all is fine
PS> $info.'Config:AccessoryOutputBins'
  
ComputerName         PrinterName          PropertyName         Type       Value          
------------         -----------          ------------         ----       -----
                     S/W Laser HP         Config:AccessoryO... String     500Stapler
  
PS> $info.'Config:AccessoryOutputBins'.Value
500Stapler  

 


Twitter This Tip! ReTweet this Tip!