Instantly share code, notes, and snippets.
Last active
April 15, 2023 04:55
-
Save neerajks77/effccba364bd9b23d19a197da5d9cc84 to your computer and use it in GitHub Desktop.
This script intakes the parameters from incoming ServiceNow Requests for Shared email creation and processes the request. Finally, it updates the serice request in ServiceNow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################################### | |
#Author:Neeraj Kumar | |
#Description:This script intakes the parameters from incoming ServiceNow Requests for Shared email creation and processes the request. Finally, it updates the serice request in ServiceNow | |
#Date: 03/10/2022 | |
############################################### | |
param( | |
[Parameter(Mandatory=$true)] | |
[string] $Source, | |
[Parameter(Mandatory=$true)] | |
[string] $ServiceRequestNumber, | |
[Parameter(Mandatory=$true)] | |
[string] $RequestItemNumber, | |
[Parameter(Mandatory=$true)] | |
[string] $SCTaskNumber, | |
[Parameter(Mandatory=$true)] | |
[string] $EmailIDtobeProvisioned, | |
[Parameter(Mandatory=$true)] | |
[string] $MailboxName, | |
[Parameter(Mandatory=$true)] | |
[string] $Owner, | |
[Parameter(Mandatory=$false)] | |
[string[]] $Users, | |
[Parameter(Mandatory=$true)] | |
[string] $Alias, | |
[Parameter(Mandatory=$false)] | |
[Boolean] $FullAccess = $false, | |
[Parameter(Mandatory=$false)] | |
[Boolean] $SendAs = $false, | |
[Parameter(Mandatory=$false)] | |
[Boolean] $CalendarAccess = $false | |
) | |
# Enforcing validation of code | |
Set-StrictMode -Version Latest | |
Function ProvisionSharedMailbox(){ | |
try{ | |
if ($EmailIDtobeProvisioned -match "^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$") | |
{ | |
Write-Output $EmailIDtobeProvisioned | |
try | |
{ | |
#Check if the email request if for the correct domain | |
$position = $EmailIDtobeProvisioned.IndexOf("@") | |
$tld = $EmailIDtobeProvisioned.Substring($position+1) | |
if($tld -ne $Organization) | |
{ | |
$Global:RequestState = "Closed_Incomplete" | |
$Global:Reason = "The email address requested is for an incorrect domain. The ticket has been marked as closed imcompleted." | |
$Global:Outputs = "The email address requested is for an incorrect domain. The ticket has been marked as closed imcompleted." | |
$Global:State = "4" | |
$Global:RequestState = "Closed_Incomplete" | |
$Global:Provisioningstate = "Failed" | |
} | |
else{ | |
#Connect to Exchange Online | |
Connect-ExchangeOnline -AppId $AppId -CertificateThumbPrint $ThumbPrint -Organization $Organization -ShowBanner:$false -ShowProgress:$false #-ErrorAction Stop | |
#Check if the email already exists for the user. If exists, update the ticket with comments | |
[string] $GetEmail = Get-Mailbox -Identity $EmailIDtobeProvisioned -ErrorAction SilentlyContinue | |
#Write 'GetEmail: ' $GetEmail | |
if (($GetEmail -eq "") -or ($GetEmail -eq $null)){ | |
Write-Output 'Correctly Inside Email Creation' | |
try{ | |
#Create Shared Mailbox | |
if ($Alias -ne '' -or $Alias -ne $null){$Alias = RemoveSpacefromText $Alias} | |
New-Mailbox -Name $MailboxName -Alias $Alias -Shared -PrimarySmtpAddress $EmailIDtobeProvisioned | |
#Check if the users array is empty or null | |
if((!$Users.count -eq 0) -or (!$Users -eq '')) | |
{ | |
#Check if 'Full Access' functionality is requestedand accordingly set permissions on Shared Mailbox | |
if($FullAccess){ | |
Add-MailboxPermission $MailboxName -User $Owner -AccessRights FullAccess -InheritanceType all | |
foreach($FAMember in $Users){ | |
Add-MailboxPermission -Identity $MailboxName -User $FAMember -AccessRights ‘FullAccess’ -InheritanceType All | |
} | |
} | |
#Check if 'Send As' functionality is requestedand accordingly set permissions on Shared Mailbox | |
if($SendAs){ | |
Add-RecipientPermission $MailboxName -Trustee $Owner -AccessRights SendAs -confirm:$False | |
foreach($SAMember in $Users){ | |
Add-RecipientPermission $MailboxName -Trustee $SAMember -AccessRights SendAs -confirm:$False | |
} | |
} | |
#Check if 'Calenar Access' is requestedand accordingly set permissions on Shared Mailbox | |
if($CalendarAccess){ | |
$MailBoxCalendar = $MailboxName + ":\calendar" | |
Add-MailboxFolderPermission –Identity $MailBoxCalendar -AccessRight PublishingEditor -User $Owner | |
foreach($CMember in $Users){ | |
Add-MailboxFolderPermission –Identity $MailBoxCalendar -AccessRight PublishingEditor -User $CMember | |
} | |
} | |
} | |
else{ | |
if($FullAccess){ | |
#Give full Access as Owner to the Shared Mailbox requester by default | |
Add-MailboxPermission $MailboxName -User $Owner -AccessRights FullAccess -InheritanceType all | |
} | |
if($SendAs){ | |
#Give 'Send As' permission to the requester by default | |
Add-RecipientPermission $MailboxName -Trustee $Owner -AccessRights SendAs -confirm:$False | |
} | |
if($CalendarAccess){ | |
#Assign permission to the Mailbox Calendar | |
$MailBoxCalendar = $MailboxName + ":\calendar" | |
Add-MailboxFolderPermission –Identity $MailBoxCalendar -AccessRight PublishingEditor -User $Owner | |
} | |
} | |
$Global:Reason = "Shared Mailbox has been provisioned with Email ID - " + $EmailIDtobeProvisioned + " and the users have been added tothe Shared Mailbox. Request has been Completed." | |
$Global:Outputs = "Shared Mailbox has been provisioned with Email ID - " + $EmailIDtobeProvisioned + " and the users have been added tothe Shared Mailbox. Request has been Completed." | |
$Global:State = "3" | |
$Global:RequestState = "Closed_Complete" | |
$Global:Provisioningstate = "Succeeded" | |
} | |
catch{ | |
$Global:Reason = $_.Exception.ToString() | |
$Global:Outputs = $_.Exception.ToString() | |
$Global:State = "4" | |
$Global:RequestState = "Closed_Incomplete" | |
$Global:Provisioningstate = "Failed" | |
} | |
} | |
else{ | |
$Global:RequestState = "Closed_Incomplete" | |
$Global:Reason = "The shared email address requested already exists. The ticket has been marked as closed imcompleted." | |
$Global:Outputs = "The shared email address requested already exists. The ticket has been marked as closed imcompleted." | |
$Global:State = "4" | |
$Global:RequestState = "Closed_Incomplete" | |
$Global:Provisioningstate = "Failed" | |
} | |
} | |
} | |
Catch | |
{ | |
$Global:Reason = $_.Exception.ToString() | |
$Global:Outputs = $_.Exception.ToString() | |
$Global:State = "4" | |
$Global:RequestState = "Closed_Incomplete" | |
$Global:Provisioningstate = "Failed" | |
} | |
} | |
# GetSNOWAuthorizationToken | |
# UpdateRITMPostProcessingtheRequest | |
} | |
Catch | |
{ | |
$Global:Reason = $_.Exception.ToString() | |
$Global:Outputs = $_.Exception.ToString() | |
$Global:State = "4" | |
$Global:RequestState = "Closed_Incomplete" | |
$Global:Provisioningstate = "Failed" | |
} | |
switch($Source){ | |
"SNOW"{UpdateSNOWwithTaskStatus} | |
"SelfService"{} | |
Default{ | |
"No Matches" | |
} | |
} | |
} | |
function UpdateSNOWwithTaskStatus{ | |
try{ | |
$SNOWSessionURL = $Global:SNOWURL | |
$Type = "application/json" | |
# Set headers | |
$GlobalHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" | |
$GlobalHeaders.Add('Accept', $Type) | |
$GlobalHeaders.Add('Content-Type', $Type) | |
# Build & set authentication header | |
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $Username, $Password))) | |
$GlobalHeaders.Add('Authorization', ('Basic {0}' -f $base64AuthInfo)) | |
$body = @{ | |
"closed_at"= $currentUTCtime | |
"DeploymentName" = $SCTaskNumber | |
"ritm" = $RequestItemNumber | |
"Provisioningstate" = $Global:Provisioningstate | |
"Outputs" = $Global:Outputs | |
"Reason" = $Global:Reason | |
"request_state" = $Global:RequestState | |
"close_notes"= $Global:LogMessage | |
"comments_and_work_notes" = $Global:LogMessage | |
"comments" = $Global:LogMessage | |
} | |
$bodyJSON = $body | ConvertTo-Json | |
Try | |
{ | |
write $bodyJSON | |
$result = Invoke-RestMethod -Method POST -Uri $SNOWSessionURL -Body $bodyJSON -Headers $GlobalHeaders | |
if(!$result) | |
{ | |
throw "Error Occured" | |
} | |
else | |
{ | |
Write-Output $result | |
Write-Output "Succeeded" | |
} | |
} | |
Catch | |
{ | |
$_.Exception.ToString() | |
$error[0] | Format-List -Force | |
} | |
} | |
catch{ | |
$_.Exception.ToString() | |
$error[0] | Format-List -Force | |
} | |
} | |
function RemoveSpacefromText{ | |
Param( | |
[Parameter(Mandatory=$true)] | |
[string] $paramtext | |
) | |
[string] $retval = $paramtext.replace(' ', '') | |
return $retval | |
} | |
# Initiate the variable here | |
################################## | |
[Boolean] $EmailExists = $false | |
[Boolean] $Global:EmailProvisioned = $false | |
[string] $Global:SNOWURL = Get-AutomationVariable -Name 'SNOWURL' | |
[string] $Organization = Get-AutomationVariable -Name 'Organization' | |
[string] $Thumbprint = Get-AutomationVariable -Name 'CERT_THUMBPRINT' | |
[string] $AppId = Get-AutomationVariable -Name 'AppID' | |
[string] $Global:Provisioningstate = '' | |
[string] $Global:Reason = ' ' | |
[string] $Global:Outputs = ' ' | |
[string] $Global:LogMessage = '' | |
[string] $Global:State = "2" | |
[string] $Global:RequestState = "2" | |
Connect-AzAccount -Identity | |
$VaultName = Get-AutomationVariable -Name "VaultName" | |
$SecretPassword = Get-AutomationVariable -Name "SecretPassword" | |
$CId = Get-AutomationVariable -Name "CId" | |
$CSecret = Get-AutomationVariable -Name "CSecret" | |
$Uname = Get-AutomationVariable -Name "Uname" | |
# Retrieve value from Key Vault | |
[string] $Username = Get-AzKeyVaultSecret -VaultName $VaultName -Name $Uname -AsPlainText | |
$Username = $Username.Trim() | |
[string] $Password = Get-AzKeyVaultSecret -VaultName $VaultName -Name $SecretPassword -AsPlainText | |
$Password = $Password.Trim() | |
[string] $ClientID = Get-AzKeyVaultSecret -VaultName $VaultName -Name $CId -AsPlainText | |
$ClientID = $ClientID.Trim() | |
[string] $ClientSecret = Get-AzKeyVaultSecret -VaultName $VaultName -Name $CSecret -AsPlainText | |
$ClientSecret = $ClientSecret.Trim() | |
$date = Get-Date | |
[System.DateTime] $currentUTCtime = $date.ToUniversalTime() | |
Write-Output "Hello" | |
##################################### | |
# call the function to provision email id | |
##################################### | |
ProvisionSharedMailbox | |
################################################################# End Main Section ############################################################ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment