通用打印 PowerShell 用例示例

UniversalPrintManagement PowerShell 模块支持已建立的 PowerShell 脚本模式。 本文将一些模式作为如何组合 cmdlet 以处理选择用例的起点。

非交互式通用打印连接

使用 PowerShell 的主要值之一是创建可以反复执行的非交互式脚本。 需要输入用户凭据来建立与通用打印的连接,这违背了此想法。 一个选项是解决此问题,即安全地存储用户密码密码,并根据需要检索密码。

  1. 将密码机密安全地存储到文件
  2. 在调用前检索密码 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

批注销连接or 的打印机

假设你已经知道用于注册打印机的已注册连接器的名称。 请参阅 Get-UP连接or cmdlet 检索已注册连接器的列表。

  1. 连接到通用打印
  2. 获取通过特定连接or 注册的打印机列表
  3. 删除已注册的打印机
Connect-UPService
$ConnectorPrinters = Get-UPPrinter -IncludeConnectorDetails
$ConnectorPrinters.Results | Where-Object {$_.Connectors.DisplayName -Contains "<Connector Name>"} | Remove-UPPrinter

标识共享打印机名称后面的已注册打印机

  1. 连接到通用打印
  2. 检索打印机列表并使用本地计算机筛选结果
Connect-UPService
$Printers = Get-UPPrinter
$Printer = $Printers.Results | Where-Object {$_.Shares.DisplayName -eq "<Share Name>"}

批处理取消共享打印机

  1. 连接到通用打印
  2. 获取感兴趣的打印机列表
  3. 取消共享打印机集合

注意

此示例显示所有共享打印机的未共享。 若要仅取消共享选择打印机,可以在检索打印机时添加其他筛选器。

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

Batch 授予所有用户对共享打印机的访问权限

  1. 连接到通用打印
  2. 获取感兴趣的打印机共享列表
  3. 向用户授予对打印机集合的访问权限
Connect-UPService
$PrinterShares = Get-UPPrinterShare
$PrinterShares.Results | Grant-UPAccess -AllUsersAccess

Batch 授予用户或用户组对共享打印机的访问权限

  1. 预征:检索用户 ID 和用户组 ID
  2. 连接到通用打印
  3. 获取感兴趣的打印机共享列表
  4. 授予特定用户或组对打印机集合的访问权限
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}

批处理集打印机位置属性

  1. 连接到通用打印
  2. 获取感兴趣的打印机列表
  3. 向用户授予对打印机集合的访问权限
Connect-UPService
$Printers = Get-UPPrinter
$Printers.Results | Set-UPPrinterProperty -Latitude 47.642391 -Longitude -122.137001 -Organization "Contoso" -Site "Main Campus" -City "Redmond" -Building "101"

使用 ContinuationToken

  1. 连接到通用打印
  2. 获取感兴趣的打印机列表
  3. 如果遇到间歇性故障,将返回部分结果以及继续标记。
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. ContinuationToken 使调用结果更可靠。 可以相互添加和追加重试。 请注意,只有注册的打印机/连接器/共享/等数量较高(约 8000+)的租户才需要此操作,并且在整个列表中循环访问时遇到一致的故障。
do
{
    $i = Get-UPPrinter -ContinuationToken $i.ContinuationToken 
    $allprinters += $i.Results
}
while (![string]::IsNullOrEmpty($i.ContinuationToken))

$allprinters.Results

下载上个月的扩展用户和打印机使用情况报告

  1. 确保已安装正确的 Microsoft Graph 模块
  2. 登录到 Microsoft Graph
  3. 请求所需的“Reports.Read.All”授权范围
  4. 收集并导出打印机报表
  5. 收集并导出用户报表
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'."