Forum Discussion
Twrriglesworth
Dec 09, 2024Copper Contributor
Enabling and disabling forwarding rule
Hello, We need to turn on a mail forwarding rule on a single mailbox, within 365. We looked at using a Azure Function App and copilot got us most of the way there but need some help with a 400 erro...
- Dec 09, 2024
This is just the function to turn the rule on, the plan is to have another rule to disable the rule with a time trigger
Kidd_Ip
Dec 10, 2024MVP
Try the below script, please make sure you fully understand before applying:
# Azure AD App details
$clientId = "your-client-id"
$clientSecret = "your-client-secret"
$tenantId = "your-tenant-id"
# Function parameters
$mailbox = "email address removed for privacy reasons"
$ruleId = "086b4cfe-b18a-4ca0-b8a6-c0cc13ab963e3208025663109857281" # Provided rule ID without backslash
# Get OAuth token
$body = @{
client_id = $clientId
client_secret = $clientSecret
scope = "https://graph.microsoft.com/.default"
grant_type = "client_credentials"
}
try {
$response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $response.access_token
Write-Output "Token acquired successfully."
} catch {
Write-Error "Failed to get OAuth token: $_"
return
}
# Enable the existing rule
$headers = @{
Authorization = "Bearer $token"
"Content-Type" = "application/json"
}
$body = @{
isEnabled = $true
}
try {
$jsonBody = $body | ConvertTo-Json
Write-Output "JSON Body: $jsonBody"
$response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$mailbox/mailFolders/inbox/messageRules/$ruleId" -Method Patch -Headers $headers -Body $jsonBody
Write-Output "Rule enabled successfully: $($response | ConvertTo-Json)"
} catch {
Write-Error "Failed to enable rule: $_"
Write-Output "Response Status Code: $($_.Exception.Response.StatusCode)"
Write-Output "Response Status Description: $($_.Exception.Response.StatusDescription)"
if ($_.Exception.Response -ne $null) {
$responseContent = $_.Exception.Response.Content.ReadAsStringAsync().Result
Write-Output "Response Content: $responseContent"
} else {
Write-Output "No response content available."
}
}
# Return response
Write-Output "Script completed."