유니버설 인쇄 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

참고 항목

자세한 ConvertFrom-SecureString ConvertTo-SecureString 내용은 여기에서 확인할 수 있습니다.

커넥트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

일괄 처리로 모든 사용자에게 공유 프린터에 대한 액세스 권한 부여

  1. 유니버설 인쇄에 커넥트
  2. 관심 있는 프린터 공유 목록 가져오기
  3. 프린터 컬렉션에 대한 사용자 액세스 권한 부여
Connect-UPService
$PrinterShares = Get-UPPrinterShare
$PrinterShares.Results | Grant-UPAccess -AllUsersAccess

사용자 또는 사용자 그룹에 공유 프린터에 대한 액세스 권한 일괄 처리 부여

  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을 사용하면 결과를 더 강력하게 호출할 수 있습니다. 재시도를 추가하고 서로 추가할 수 있습니다. 등록된 프린터/커넥터/공유/등이 많고 전체 목록을 반복할 때 일관된 오류가 발생하는 테넌트에만 필요합니다.
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'."