Universal Print PowerShell Use Case Samples

The UniversalPrintManagement PowerShell module supports the established PowerShell scripting patterns. This article shows some patterns as a starting point of how the cmdlets can be combined to tackle select use cases.

Non-interactive Universal Print connection

One of the main values of using PowerShell is to create non-interactive scripts that can be executed over and over again. The need to enter the user credentials to establish the connection to Universal Print goes against this idea. One option is address this is to store the user password secret securely and retrieve it as needed.

  1. Securely store password secret to a file
  2. Retrieve password just before calling Connect-UPService
$Secure = Read-Host -AsSecureString
$Encrypted = ConvertFrom-SecureString -SecureString $Secure -Key (1..16)
$Encrypted | Set-Content Encrypted.txt
...
$Secure2 = Get-Content Encrypted.txt | ConvertTo-SecureString -Key (1..16)
Connect-UPService -UserPrincipalName username@tenantname.com -Password $Secure2

Note

Additional information about ConvertFrom-SecureString and ConvertTo-SecureString is available here.

Batch unregister printers of a Connector

Assuming you already know the name of the registered Connector used to register the printers. Refer to Get-UPConnector cmdlet to retrieve the list of registered Connectors.

  1. Connect to Universal Print
  2. Get the list of printers registered through the particular Connector
  3. Remove the registered printer
Connect-UPService
$ConnectorPrinters = Get-UPPrinter -IncludeConnectorDetails
$ConnectorPrinters.Results | Where-Object {$_.Connectors.DisplayName -Contains "<Connector Name>"} | Remove-UPPrinter

Identifying the registered printer behind a shared printer name

  1. Connect to Universal Print
  2. Retrieve the list of printers and use local machine to filter the results
Connect-UPService
$Printers = Get-UPPrinter
$Printer = $Printers.Results | Where-Object {$_.Shares.DisplayName -eq "<Share Name>"}

Batch unshare printers

  1. Connect to Universal Print
  2. Get the list of printers of interest
  3. Unshare the collection of printers

Note

This example shows unsharing of all shared printers. To unshare only select printers, additional filters can be added when retrieving the printers.

Connect-UPService
$Printers = Get-UPPrinter
$Printers.Results.Shares | Remove-UPPrinterShare

Batch grant all users access to shared printers

  1. Connect to Universal Print
  2. Get the list of printer shares of interest
  3. Grant user access to the collection of printers
Connect-UPService
$PrinterShares = Get-UPPrinterShare
$PrinterShares.Results | Grant-UPAccess -AllUsersAccess

Batch grant users or user groups access to shared printers

  1. Pre-requite: Retrieve user IDs and user group IDs
  2. Connect to Universal Print
  3. Get the list of printer shares of interest
  4. Grant specific users or groups access to the collection of printers
Connect-AzAccount
$Users = Get-AzADUser -First 10
$UserGroups = Get-AzADGroup -SearchString Contoso

Connect-UPService
$PrinterShares = Get-UPPrinterShare
$Users | ForEach-Object {$PrinterShares.Results | Grant-UPAccess -UserID $_.Id}
$UserGroups | ForEach-Object {$PrinterShares.Results | Grant-UPAccess -GroupID $_.Id}

Batch set printer location properties

  1. Connect to Universal Print
  2. Get the list of printers of interest
  3. Grant user access to the collection of printers
Connect-UPService
$Printers = Get-UPPrinter
$Printers.Results | Set-UPPrinterProperty -Latitude 47.642391 -Longitude -122.137001 -Organization "Contoso" -Site "Main Campus" -City "Redmond" -Building "101"

Using ContinuationToken

  1. Connect to Universal Print
  2. Get the list of printers of interest
  3. If an intermittent failure is encountered, partial results will be returned, along with a continuation token.
Connect-UPService
$Printers = Get-UPPrinter

"Get-UPPrinter :
At line:1 char:13
+ $Printers = Get-UPPrinter
+             ~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (System.Collecti...Models.Printer]:List`1) [Get-UPPrinter], FailedCmdletException
    + FullyQualifiedErrorId : Rerun with -ContinuationToken to continue from last cutoff: MyZRVkZCUVVGQlFVRXZMeTh2THk4dkx5OHZMMGxCUVVGQk5IQTRiR
   EY0YWpOdU1DdEtPSG94T1dwUWNHWm5kejA5,Microsoft.UPManagement.Cmdlets.GetPrinter"

$Printers.Results
"(Partial results list of printers)"

$Printers.ContinuationToken
"MyZRVkZCUVVGQlFVRXZMeTh2THk4dkx5OHZMMGxCUVVGQk5IQTRiREY0YWpOdU1DdEtPSG94T1dwUWNHWm5kejA5"

$MorePrinters = Get-UPPrinter -ContinuationToken $Printers.ContinuationToken
$MorePrinters.Results
"(Printer results list continued from previously left off)"
  1. The ContinuationToken makes calling for results more robust. Retries can be added and appended to each other. Note that this is only needed for tenants that have a high number (~8000+) of registered printers/connectors/shares/etc. and are experiencing consistent failures when iterating through the entire list.
do
{
    $i = Get-UPPrinter -ContinuationToken $i.ContinuationToken 
    $allprinters += $i.Results
}
while (![string]::IsNullOrEmpty($i.ContinuationToken))

$allprinters.Results

Download extended User and Printer usage reports for the last month

  1. Make sure the correct Microsoft Graph module is installed
  2. Sign into Microsoft Graph
  3. Request the required "Reports.Read.All" authorization scope
  4. Gather & export the Printer report
  5. Gather & export the User report
Param (
    # Date should be in this format: 2020-09-01
    # Default is the first day of the previous month at 00:00:00 (Tenant time zone)
    $StartDate = "",
    # Date should be in this format: 2020-09-30
    # Default is the last day of the previous month 23:59:59 (Tenant time zone)
    $EndDate = "",
    # Set if only the Printer report should be generated
    [switch]$PrinterOnly,
    # Set if only the User report should be generated
    [switch]$UserOnly
)

#############################
# INSTALL & IMPORT MODULES
#############################

if(-not (Get-Module Microsoft.Graph.Reports -ListAvailable)){
    Write-Progress -Activity "Installing Universal Print dependencies..." -PercentComplete 60
    Install-Module Microsoft.Graph.Reports -Scope CurrentUser -Force
}
Import-Module Microsoft.Graph.Reports

#############################
# SET DATE RANGE
#############################
if ($StartDate -eq "") {
    $StartDate = (Get-Date -Day 1).AddMonths(-1).ToString("yyyy-MM-ddT00:00:00Z")
} else {
    $StartDate = ([DateTime]$StartDate).ToString("yyyy-MM-ddT00:00:00Z")
}

if ($EndDate -eq "") {
    $EndDate = (Get-Date -Day 1).AddDays(-1).ToString("yyyy-MM-ddT23:59:59Z")
} else {
    $EndDate = ([DateTime]$EndDate).ToString("yyyy-MM-ddT23:59:59Z")
}

echo "Gathering reports between $StartDate and $EndDate."

########################################
# SIGN IN & CONNECT TO MICROSOFT GRAPH
########################################

# These scopes are needed to get the list of users, list of printers, and to read the reporting data.
Connect-MgGraph -Scopes "Reports.Read.All"

##########################
# GET PRINTER REPORT
##########################

if (!$UserOnly)
{
    Write-Progress -Activity "Gathering Printer usage..." -PercentComplete -1

    # Get the printer usage report
    $printerReport = Get-MgReportMonthlyPrintUsageByPrinter -All -Filter "completedJobCount gt 0 and usageDate ge $StartDate and usageDate lt $EndDate"

    ## Join extended printer info with the printer usage report
    $reportWithPrinterNames = $printerReport | 
        Select-Object ( 
            @{Name = "UsageMonth"; Expression = {$_.Id.Substring(0,8)}}, 
            @{Name = "PrinterId"; Expression = {$_.PrinterId}}, 
            @{Name = "DisplayName"; Expression = {$_.PrinterName}}, 
            @{Name = "TotalJobs"; Expression = {$_.CompletedJobCount}},
            @{Name = "ColorJobs"; Expression = {$_.CompletedColorJobCount}},
            @{Name = "BlackAndWhiteJobs"; Expression = {$_.CompletedBlackAndWhiteJobCount}},
            @{Name = "ColorPages"; Expression = {$_.ColorPageCount}},
            @{Name = "BlackAndWhitePages"; Expression = {$_.BlackAndWhitePageCount}},
            @{Name = "TotalSheets"; Expression = {$_.MediaSheetCount}})

    # Write the aggregated report CSV
    $printerReport | Export-Csv -Path .\printerReport.csv
}

##################
# GET USER REPORT
##################

if (!$PrinterOnly)
{
    Write-Progress -Activity "Gathering User usage..." -PercentComplete -1

    # Get the user usage report
    $userReport = Get-MgReportMonthlyPrintUsageByUser -All -Filter "completedJobCount gt 0 and usageDate ge $StartDate and usageDate lt $EndDate"
    $reportWithUserInfo = $userReport | 
        Select-Object ( 
            @{Name = "UsageMonth"; Expression = {$_.Id.Substring(0,8)}}, 
            @{Name = "UserPrincipalName"; Expression = {$_.UserPrincipalName}}, 
            @{Name = "TotalJobs"; Expression = {$_.CompletedJobCount}},
            @{Name = "ColorJobs"; Expression = {$_.CompletedColorJobCount}},
            @{Name = "BlackAndWhiteJobs"; Expression = {$_.CompletedBlackAndWhiteJobCount}},
            @{Name = "ColorPages"; Expression = {$_.ColorPageCount}},
            @{Name = "BlackAndWhitePages"; Expression = {$_.BlackAndWhitePageCount}},
            @{Name = "TotalSheets"; Expression = {$_.MediaSheetCount}})
			        
    $reportWithUserInfo | Export-Csv -Path .\userReport.csv
}

echo "Reports were written to 'printerReport.csv' and 'userReport.csv'."