param( [string]$Identity ) try { # Import credentials and establish a PowerShell session to Exchange Server $serverAddress = Get-Content -Path ".\DefaultServer.txt" $currentDomain = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).Name $credential = Import-Clixml -Path ".\AdminCredential.xml" $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$serverAddress/PowerShell/ -Authentication Kerberos -Credential $credential Import-PSSession $session -DisableNameChecking # Ensure Identity is in the correct format if ($Identity -notlike "*@*") { $Identity = "$Identity@$currentDomain" } # Retrieve DisplayName and Department from Active Directory $user = Get-ADUser -Filter "UserPrincipalName -eq '$Identity'" -Property DisplayName, Department if ($user) { $DisplayName = $user.DisplayName $Department = $user.Department # Debugging output Write-Host "DisplayName: $DisplayName" -ForegroundColor Yellow Write-Host "Department: $Department" -ForegroundColor Yellow # Handle missing or empty variables if (-not $DisplayName) { $DisplayName = "Name not available" } if (-not $Department) { $Department = "Department not available" } # Set custom AutoReply message Set-MailboxAutoReplyConfiguration -Identity $Identity -AutoReplyState Enabled -ExternalAudience All -InternalMessage "Thank you for your email. Please be informed that $DisplayName is no longer working at $Department.`nThis mailbox is currently unattended.`nInformation Classification: Restricted." -ExternalMessage "Thank you for your email. Please be informed that $DisplayName is no longer working at $Department.`nThis mailbox is currently unattended.`nInformation Classification: Restricted." Write-Host "Custom AutoReply message set for $Identity." -ForegroundColor Green } else { Write-Host "User not found in Active Directory for $Identity." -ForegroundColor Red } # Remove the session after completing tasks Remove-PSSession $session } catch { Write-Host "Failed to set AutoReply message for $Identity. Error:" -ForegroundColor Red Write-Host $_ }