Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#PSScriptInfo
- .VERSION 1.0
- .GUID
- .AUTHOR
- .COMPANYNAME
- .COPYRIGHT
- .TAGS
- .LICENSEURI
- .PROJECTURI
- .ICONURI
- .EXTERNALMODULEDEPENDENCIES
- .REQUIREDSCRIPTS
- .EXTERNALSCRIPTDEPENDENCIES
- .RELEASENOTES
- #>
- <#
- .DESCRIPTION
- Creates TAP (Temporary Access Pass) for new Employee and assembles onboarding guide.
- #>
- #Requires -modules Microsoft.Graph.Identity.SignIns
- #Requires -modules Microsoft.Graph.Users.Actions
- #Requires -modules Microsoft.Graph.Users
- Param(
- [Parameter(Position = 0, mandatory = $false)]
- [string]$userID, # User ID to create TAP for access
- [Parameter(Position = 1, mandatory = $false)]
- [string]$CertThumbprint, # Application Client Id
- [Parameter(Position = 2, mandatory = $false)]
- [string]$usableOnce = $false, # Use once or multiple times
- [Parameter(Position = 3, mandatory = $false)]
- [string]$lifeTimeInMinutes = 20160, # Lifetime in minutes
- [Parameter(Position = 4, mandatory = $false)]
- [string]$emailAddress, # Lifetime in minutes
- [Parameter(Position = 5, mandatory = $false)]
- [string]$clientID, # Application Client Id
- [Parameter(Position = 6, mandatory = $false)]
- [string]$submitterEmail # Application Client Id
- )
- #Preferences
- $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
- #Authenticate to Azure
- try {
- Connect-AzAccount -Identity -ErrorAction Stop | Out-Null
- }
- catch {
- }
- #Authenticate to MgGraph
- try {
- if (($Cert = Get-ChildItem Cert:\LocalMachine\My\$CertThumbprint)) {
- Connect-MgGraph -ClientId $clientID -TenantId (Get-AzContext).Tenant -Certificate $Cert | Out-Null
- }
- else {
- $Cert = Get-ChildItem Cert:\CurrentUser\My\$CertThumbprint
- Connect-MgGraph -ClientId $clientID -TenantId (Get-AzContext).Tenant -Certificate $Cert | Out-Null
- }
- }
- catch {
- throw $_
- break
- }
- #Test for existence of user
- if (Get-MgUser -UserId $userID) {
- <# Action to perform if the condition is true #>
- Write-Output "User was detected in system, advancing to create TAP."
- }
- else {
- <# Sleep for 60 seconds while user is synced #>
- Start-Sleep -Seconds 180
- if (Get-MgUser -UserId $userID) {
- <# Action to perform if the condition is true #>
- Write-Output "User was detected in system, advancing to create TAP."
- }
- else {
- #Stop due to user not in system
- Write-Output "User was not detected in system, exiting runbook."
- break
- }
- }
- #Set working directory // Detects latest "Sandbox" and sets directory location // This section is used if using in Azure Automation Accounts Hybrid Worker. If not you can strip down to use a static $homeDir
- $sandboxRoot = "C:\ProgramData\Microsoft\System Center\Orchestrator"
- $sandboxRootFolder = Get-ChildItem -Path $sandboxRoot -Directory -Recurse -Filter "Sandboxes"
- $availableSandboxes = Get-ChildItem -Path $sandboxRootFolder.FullName -Directory
- $sandbox = $availableSandboxes | Sort-Object -Property LastWriteTime -Descending
- $homeDir = $sandbox[0].FullName + "\Temp"
- Set-Location $homeDir
- try {
- # Create a Temporary Access Pass for a user Variables
- $properties = @{}
- $properties.isUsableOnce = $usableOnce
- $properties.startDateTime = (Get-Date).AddMinutes(2)
- $properties.lifetimeInMinutes = $lifeTimeInMinutes
- $propertiesJSON = $properties | ConvertTo-Json
- $temporaryAccessPassResult = New-MgUserAuthenticationTemporaryAccessPassMethod -UserId $userID -BodyParameter $propertiesJSON
- }
- catch {
- <#Do this if a terminating exception happens#>
- }
- try {
- #Storage Account Details
- $storageAccountName = "xxx"
- $containerName = "xxx"
- $storageContext = New-AzStorageContext -StorageAccountName $storageAccountName
- $imageFileRoot = "xxx"
- #Create Local folder for images
- New-Item -Path ($homeDir + "\" + $imageFileRoot) -ItemType Directory
- # List blobs in the container
- $imageBlobs = Get-AzStorageBlob -Context $storageContext -Container $containerName -Prefix $imageFileRoot
- # Download each blob to the local directory
- foreach ($blob in $imageBlobs) {
- $blobName = $blob.Name
- $destinationPath = (Join-Path -Path $homeDir -ChildPath $blobName)
- Get-AzStorageBlobContent -Blob $blobName -Container $containerName -Destination $destinationPath -Context $storageContext -InformationAction SilentlyContinue -Force | Out-Null
- #Write-Output "Blob '$blobName' downloaded to '$destinationPath'."
- }
- Write-Output "All blobs downloaded successfully."
- }
- catch {
- throw $_
- break
- }
- try {
- #Onboarding Form PDF
- #Variables
- $htmlFilePath = "$homeDir\$imageFileRoot\Welcome.html"
- #Update Information in HTML
- # Read the content of the HTML file
- $htmlContent = Get-Content -Path $htmlFilePath -Raw
- # Define the values to replace
- $displayName = (Get-MgUser -UserId $userID).DisplayName
- $tempAccessPass = $temporaryAccessPassResult.TemporaryAccessPass
- $htmlFilePathOut = $homeDir + "\$imageFileRoot\" + $displayName + ".html"
- $pdfOutputPath = ($homeDir + "\$imageFileRoot\" + $displayName + ".pdf")
- #Quote PDF Path
- $pdfOutputPath = '"' + $pdfOutputPath + '"'
- # Perform replacements
- $htmlContent = $htmlContent -replace '\$displayName', $displayName
- $htmlContent = $htmlContent -replace '\$userID', $userID
- $htmlContent = $htmlContent -replace '\$tempPass', $(Get-AutomationVariable -Name TMPOnboardPW)
- $htmlContent = $htmlContent -replace '\$tempAccessPass', $tempAccessPass
- # Write the updated content back to the file
- $htmlContent | Set-Content -Path $htmlFilePathOut
- $htmlFilePathOutURI = "file:///" + [uri]::EscapeUriString((Get-Item -Path $htmlFilePathOut).FullName).Replace('%5C', '/')
- Write-Output $htmlFilePathOutURI
- }
- catch {
- Write-Error "Error occurred: $_"
- break
- }
- try {
- #Launch Chrome in headless mode to print pdf
- Write-Output "Attempting to print to PDF"
- $argumentList = @(
- "--headless",
- "--disable-gpu",
- "--print-to-pdf=$pdfOutputPath",
- "--no-startup-window",
- "--no-pdf-header-footer",
- "$htmlFilePathOutURI"
- ) -join " "
- Start-Process -FilePath "C:\Program Files\Google\Chrome\Application\chrome.exe" -ArgumentList $argumentList -Wait
- }
- catch {
- throw
- break
- }
- try {
- Write-Host "Sending Email"
- $startDate = $properties.startDateTime
- $lifetime = (Get-Date).AddMinutes($properties.lifetimeInMinutes) # Replace with your actual lifetime in minutes
- $temporaryAccessPass = $temporaryAccessPassResult.TemporaryAccessPass # Replace with actual temporary access pass
- $emailBody = @"
- <html>
- <head>
- <style>
- body {
- font-family: Arial, sans-serif;
- line-height: 1.6;
- }
- .container {
- max-width: 600px;
- margin: 0 auto;
- padding: 20px;
- border: 1px solid #ddd;
- border-radius: 8px;
- background-color: #f9f9f9;
- }
- .info {
- background-color: #e7f3fe;
- padding: 10px;
- border-radius: 5px;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <h2>Temporary Access Pass</h2>
- <p>Hello,</p>
- <p>Here is the temporary access pass information for ${$userID}:</p>
- <div class="info">
- <p><strong>Email:</strong> ${userID}</p>
- <p><strong>TAP Start Time:</strong> $startDate</p>
- <p><strong>TAP Validity:</strong> $lifetime</p>
- <p><strong>TAP Credential:</strong> $temporaryAccessPass</p>
- </div>
- </div>
- </body>
- </html>
- "@
- $attachmentFilePath = ($homeDir + "\$imageFileRoot\" + $displayName + ".pdf")
- $attachmentContent = [System.IO.File]::ReadAllBytes($attachmentFilePath)
- if ($attachmentContent) {
- #IF statement to verify content has been loaded
- $attachmentBase64 = [System.Convert]::ToBase64String($attachmentContent)
- $attachmentName = (Get-Item $attachmentFilePath).Name
- $params = @{
- Message = @{
- Subject = "Onboarding: $userID"
- Body = @{
- ContentType = "HTML"
- Content = $emailBody
- }
- Attachments = @(
- @{
- "@odata.type" = "#microsoft.graph.fileAttachment"
- Name = $attachmentName
- ContentBytes = $attachmentBase64
- }
- )
- ToRecipients = @(
- @{
- EmailAddress = @{
- Address = $submitterEmail
- }
- }
- )
- }
- SaveToSentItems = $false # Use $false instead of "false"
- }
- # Send the email
- Send-MgUserMail -UserId $emailAddress -BodyParameter $params
- }
- }
- catch {
- Write-Error "Error occurred: $_"
- }
- #Clean Up
- Get-ChildItem -Path $homeDir -Recurse | Remove-Item -Recurse -Force
Add Comment
Please, Sign In to add comment