Guest User

Onboarding TAP

a guest
Jul 2nd, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.50 KB | None | 0 0
  1.  
  2. <#PSScriptInfo
  3.  
  4. .VERSION 1.0
  5.  
  6. .GUID
  7.  
  8. .AUTHOR
  9.  
  10. .COMPANYNAME
  11.  
  12. .COPYRIGHT
  13.  
  14. .TAGS
  15.  
  16. .LICENSEURI
  17.  
  18. .PROJECTURI
  19.  
  20. .ICONURI
  21.  
  22. .EXTERNALMODULEDEPENDENCIES
  23.  
  24. .REQUIREDSCRIPTS
  25.  
  26. .EXTERNALSCRIPTDEPENDENCIES
  27.  
  28. .RELEASENOTES
  29.  
  30.  
  31. #>
  32.  
  33. <#
  34.  
  35. .DESCRIPTION
  36. Creates TAP (Temporary Access Pass) for new Employee and assembles onboarding guide.
  37.  
  38. #>
  39.  
  40. #Requires -modules Microsoft.Graph.Identity.SignIns
  41. #Requires -modules Microsoft.Graph.Users.Actions
  42. #Requires -modules Microsoft.Graph.Users
  43.  
  44.  
  45. Param(
  46. [Parameter(Position = 0, mandatory = $false)]
  47. [string]$userID, # User ID to create TAP for access
  48. [Parameter(Position = 1, mandatory = $false)]
  49. [string]$CertThumbprint, # Application Client Id
  50. [Parameter(Position = 2, mandatory = $false)]
  51. [string]$usableOnce = $false, # Use once or multiple times
  52. [Parameter(Position = 3, mandatory = $false)]
  53. [string]$lifeTimeInMinutes = 20160, # Lifetime in minutes
  54. [Parameter(Position = 4, mandatory = $false)]
  55. [string]$emailAddress, # Lifetime in minutes
  56. [Parameter(Position = 5, mandatory = $false)]
  57. [string]$clientID, # Application Client Id
  58. [Parameter(Position = 6, mandatory = $false)]
  59. [string]$submitterEmail # Application Client Id
  60.  
  61.  
  62. )
  63. #Preferences
  64. $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
  65.  
  66.  
  67. #Authenticate to Azure
  68. try {
  69. Connect-AzAccount -Identity -ErrorAction Stop | Out-Null
  70. }
  71. catch {
  72.  
  73. }
  74.  
  75. #Authenticate to MgGraph
  76. try {
  77. if (($Cert = Get-ChildItem Cert:\LocalMachine\My\$CertThumbprint)) {
  78. Connect-MgGraph -ClientId $clientID -TenantId (Get-AzContext).Tenant -Certificate $Cert | Out-Null
  79. }
  80. else {
  81. $Cert = Get-ChildItem Cert:\CurrentUser\My\$CertThumbprint
  82. Connect-MgGraph -ClientId $clientID -TenantId (Get-AzContext).Tenant -Certificate $Cert | Out-Null
  83. }
  84. }
  85. catch {
  86. throw $_
  87. break
  88. }
  89.  
  90. #Test for existence of user
  91. if (Get-MgUser -UserId $userID) {
  92. <# Action to perform if the condition is true #>
  93. Write-Output "User was detected in system, advancing to create TAP."
  94. }
  95. else {
  96. <# Sleep for 60 seconds while user is synced #>
  97. Start-Sleep -Seconds 180
  98.  
  99. if (Get-MgUser -UserId $userID) {
  100. <# Action to perform if the condition is true #>
  101. Write-Output "User was detected in system, advancing to create TAP."
  102. }
  103. else {
  104. #Stop due to user not in system
  105. Write-Output "User was not detected in system, exiting runbook."
  106. break
  107. }
  108. }
  109.  
  110. #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
  111. $sandboxRoot = "C:\ProgramData\Microsoft\System Center\Orchestrator"
  112. $sandboxRootFolder = Get-ChildItem -Path $sandboxRoot -Directory -Recurse -Filter "Sandboxes"
  113. $availableSandboxes = Get-ChildItem -Path $sandboxRootFolder.FullName -Directory
  114. $sandbox = $availableSandboxes | Sort-Object -Property LastWriteTime -Descending
  115. $homeDir = $sandbox[0].FullName + "\Temp"
  116. Set-Location $homeDir
  117.  
  118. try {
  119. # Create a Temporary Access Pass for a user Variables
  120. $properties = @{}
  121. $properties.isUsableOnce = $usableOnce
  122. $properties.startDateTime = (Get-Date).AddMinutes(2)
  123. $properties.lifetimeInMinutes = $lifeTimeInMinutes
  124. $propertiesJSON = $properties | ConvertTo-Json
  125. $temporaryAccessPassResult = New-MgUserAuthenticationTemporaryAccessPassMethod -UserId $userID -BodyParameter $propertiesJSON
  126. }
  127. catch {
  128. <#Do this if a terminating exception happens#>
  129. }
  130.  
  131. try {
  132. #Storage Account Details
  133. $storageAccountName = "xxx"
  134. $containerName = "xxx"
  135. $storageContext = New-AzStorageContext -StorageAccountName $storageAccountName
  136. $imageFileRoot = "xxx"
  137.  
  138. #Create Local folder for images
  139. New-Item -Path ($homeDir + "\" + $imageFileRoot) -ItemType Directory
  140.  
  141. # List blobs in the container
  142. $imageBlobs = Get-AzStorageBlob -Context $storageContext -Container $containerName -Prefix $imageFileRoot
  143.  
  144. # Download each blob to the local directory
  145. foreach ($blob in $imageBlobs) {
  146. $blobName = $blob.Name
  147. $destinationPath = (Join-Path -Path $homeDir -ChildPath $blobName)
  148. Get-AzStorageBlobContent -Blob $blobName -Container $containerName -Destination $destinationPath -Context $storageContext -InformationAction SilentlyContinue -Force | Out-Null
  149. #Write-Output "Blob '$blobName' downloaded to '$destinationPath'."
  150. }
  151.  
  152. Write-Output "All blobs downloaded successfully."
  153. }
  154. catch {
  155. throw $_
  156. break
  157. }
  158.  
  159. try {
  160. #Onboarding Form PDF
  161. #Variables
  162. $htmlFilePath = "$homeDir\$imageFileRoot\Welcome.html"
  163. #Update Information in HTML
  164.  
  165. # Read the content of the HTML file
  166. $htmlContent = Get-Content -Path $htmlFilePath -Raw
  167.  
  168. # Define the values to replace
  169. $displayName = (Get-MgUser -UserId $userID).DisplayName
  170. $tempAccessPass = $temporaryAccessPassResult.TemporaryAccessPass
  171. $htmlFilePathOut = $homeDir + "\$imageFileRoot\" + $displayName + ".html"
  172. $pdfOutputPath = ($homeDir + "\$imageFileRoot\" + $displayName + ".pdf")
  173. #Quote PDF Path
  174. $pdfOutputPath = '"' + $pdfOutputPath + '"'
  175.  
  176. # Perform replacements
  177. $htmlContent = $htmlContent -replace '\$displayName', $displayName
  178. $htmlContent = $htmlContent -replace '\$userID', $userID
  179. $htmlContent = $htmlContent -replace '\$tempPass', $(Get-AutomationVariable -Name TMPOnboardPW)
  180. $htmlContent = $htmlContent -replace '\$tempAccessPass', $tempAccessPass
  181.  
  182. # Write the updated content back to the file
  183. $htmlContent | Set-Content -Path $htmlFilePathOut
  184. $htmlFilePathOutURI = "file:///" + [uri]::EscapeUriString((Get-Item -Path $htmlFilePathOut).FullName).Replace('%5C', '/')
  185. Write-Output $htmlFilePathOutURI
  186. }
  187. catch {
  188. Write-Error "Error occurred: $_"
  189. break
  190. }
  191.  
  192. try {
  193. #Launch Chrome in headless mode to print pdf
  194. Write-Output "Attempting to print to PDF"
  195.  
  196. $argumentList = @(
  197. "--headless",
  198. "--disable-gpu",
  199. "--print-to-pdf=$pdfOutputPath",
  200. "--no-startup-window",
  201. "--no-pdf-header-footer",
  202. "$htmlFilePathOutURI"
  203. ) -join " "
  204.  
  205. Start-Process -FilePath "C:\Program Files\Google\Chrome\Application\chrome.exe" -ArgumentList $argumentList -Wait
  206.  
  207. }
  208. catch {
  209. throw
  210. break
  211. }
  212.  
  213. try {
  214.  
  215. Write-Host "Sending Email"
  216. $startDate = $properties.startDateTime
  217. $lifetime = (Get-Date).AddMinutes($properties.lifetimeInMinutes) # Replace with your actual lifetime in minutes
  218. $temporaryAccessPass = $temporaryAccessPassResult.TemporaryAccessPass # Replace with actual temporary access pass
  219.  
  220. $emailBody = @"
  221. <html>
  222. <head>
  223. <style>
  224. body {
  225. font-family: Arial, sans-serif;
  226. line-height: 1.6;
  227. }
  228. .container {
  229. max-width: 600px;
  230. margin: 0 auto;
  231. padding: 20px;
  232. border: 1px solid #ddd;
  233. border-radius: 8px;
  234. background-color: #f9f9f9;
  235. }
  236. .info {
  237. background-color: #e7f3fe;
  238. padding: 10px;
  239. border-radius: 5px;
  240. }
  241. </style>
  242. </head>
  243. <body>
  244. <div class="container">
  245. <h2>Temporary Access Pass</h2>
  246. <p>Hello,</p>
  247. <p>Here is the temporary access pass information for ${$userID}:</p>
  248. <div class="info">
  249. <p><strong>Email:</strong> ${userID}</p>
  250. <p><strong>TAP Start Time:</strong> $startDate</p>
  251. <p><strong>TAP Validity:</strong> $lifetime</p>
  252. <p><strong>TAP Credential:</strong> $temporaryAccessPass</p>
  253. </div>
  254. </div>
  255. </body>
  256. </html>
  257. "@
  258.  
  259. $attachmentFilePath = ($homeDir + "\$imageFileRoot\" + $displayName + ".pdf")
  260. $attachmentContent = [System.IO.File]::ReadAllBytes($attachmentFilePath)
  261. if ($attachmentContent) {
  262. #IF statement to verify content has been loaded
  263. $attachmentBase64 = [System.Convert]::ToBase64String($attachmentContent)
  264. $attachmentName = (Get-Item $attachmentFilePath).Name
  265.  
  266. $params = @{
  267. Message = @{
  268. Subject = "Onboarding: $userID"
  269. Body = @{
  270. ContentType = "HTML"
  271. Content = $emailBody
  272. }
  273. Attachments = @(
  274. @{
  275. "@odata.type" = "#microsoft.graph.fileAttachment"
  276. Name = $attachmentName
  277. ContentBytes = $attachmentBase64
  278. }
  279. )
  280. ToRecipients = @(
  281. @{
  282. EmailAddress = @{
  283. Address = $submitterEmail
  284. }
  285. }
  286. )
  287. }
  288. SaveToSentItems = $false # Use $false instead of "false"
  289. }
  290.  
  291. # Send the email
  292. Send-MgUserMail -UserId $emailAddress -BodyParameter $params
  293. }
  294.  
  295. }
  296. catch {
  297. Write-Error "Error occurred: $_"
  298. }
  299.  
  300. #Clean Up
  301. Get-ChildItem -Path $homeDir -Recurse | Remove-Item -Recurse -Force
Add Comment
Please, Sign In to add comment