Adding teammates using API through Powershell

54 Views Asked by At

I want to automate a process of adding new teammates to sendgrid. I manually used to add them via CURL which worked. To fully automate this I would need to achieve the same via Powershell. I converted the curl over to invoke-restmethod and it is throwing invalid JSON error. After spending a day it seems to me the body is exactly the same as the CURL request but it still fails. Can anyone help me with this? Below is the code I'm using:

$uri = "https://api.sendgrid.com/v3/teammates"
$emails = "[email protected]", "[email protected]"
$subusers = "subuser1", "subuser2"
$sendgridApiKey= "full_admin_key"

foreach ($email in $emails){
    foreach ($subuser in $subusers){

        $headers = @{"Authorization" = "Bearer " + $sendgridApiKey; "Content-Type"=          "application/json"; "on-behalf-of" = $subuser}
        $Body = @{
            email= "$email"
            scopes="alerts.create","alerts.read"
            is_admin="false"} | ConvertTo-Json

        echo "Inviting $email to subuser $subuser"
        #echo Invoke-RestMethod -Uri $Uri -Method Post -Headers $headers -Body $body
        Invoke-RestMethod -Uri $Uri -Method Post -Headers $headers -Body $body
    }
}

Original curl:

declare -a emails= ([email protected])
declare -a subusers= (realsubuser1 realsubuser2)
set -a 
sendgridApiKey="RealOneInScript"
set +a
for e in ${emails[@]}
do
    for s in ${subusers[@]}
    do
    
        echo "Inviting $e to subuser $s"
        #invite user, scope is applicable to marketing users
        curl -X "POST" "https://api.sendgrid.com/v3/teammates" -H "on-behalf-of:$s"  -H "Authorization: Bearer $sendgridApiKey" -H "Content-Type: application/json" -d \
        '{
        "email":"'$e'","validations.email.read","validations.email.create","email_testing.read", "2fa_required"],
        "is_admin":false
        }'
    sleep 10 
    done
done
1

There are 1 best solutions below

1
On BEST ANSWER

It could be is_admin value - it should be Boolean type instead of string - try

        $Body = @{
            email= "$email"
            scopes="alerts.create","alerts.read"
            is_admin=$false} | ConvertTo-Json