Skip to content

Instantly share code, notes, and snippets.

@panreel
Last active October 3, 2018 12:30
Show Gist options
  • Select an option

  • Save panreel/ca7853d0696c1ff86d93de477b5966e1 to your computer and use it in GitHub Desktop.

Select an option

Save panreel/ca7853d0696c1ff86d93de477b5966e1 to your computer and use it in GitHub Desktop.
Change Username to WP Accounts by using SCIM API and PowerShell

Bulk Editing Emails for Workplace users

This PowerShell script allows to change the email address field for Workplace users in bulk.

Setup

  • Create a new Custom Integration in the Workplace Admin Panel: Create a custom Integration.
    This requires at least "Manage Accounts" permissions. Take note of the Access Token.

  • Create a file named accessToken.js with the following content:

    {
          "accessToken" : "YOUR-ACCESS-TOKEN"
    }
  • Export your users' profile data: As an admin, you can export profile data by going to the People Tab in the Admin Portal > Edit People button > Download File button in the dialog window that will open. You will then receive an email message with a link to download a XLSX file containing the exported user data.

  • Add a NewEmail column in the XLSX file and fill it with the new email address for the users you would like to update profile data.

    Full Name Email ... NewEmail
    Fox A foxA@xyz.com ... foxie@xyz.com
    Fox B foxB@xyz.com ... vulpis@xyz.com
    Fox C foxC@yyy.com ... wolfie@zzz.com

    Note: The script will skip the email update for a user if the NewEmail field is empty or no Email field is populated (e.g. Email-less accounts).

    Note: Please be aware of the column name format. It is NewEmail without spaces (e.g. no New Email). Please also be sure the file uses a plain formatting (no tables, etc.).

Run

  • Run the script by passing the XLSX file and accessToken.js file as input:

    ./changeBulkEmail.ps1 -WPExportedUsers workplace_users.xlsx -WPAccessToken accessToken.js -Interactive

    Here are the details of the passed params:

    Parameter Description Type Required
    WPExportedUsers The path for the XLSX file with the exported user data String Yes
    WPAccessToken The path for the JSON file with the access token String Yes
    Interactive If the script should prompt for a user OK for each entry Switch No
param(
[Parameter(Mandatory=$true, Position=0, HelpMessage='Path for your Workplace export file')] [string]$WPExportedUsers,
[Parameter(Mandatory=$true, Position=1, HelpMessage='Path for your Workplace access token in .json format {"accessToken" : 123xyz}')] [string]$WPAccessToken,
[switch]$Interactive
)
#Install ImportExcel Module
If(!(Get-module ImportExcel)){Install-Module ImportExcel -scope CurrentUser}
#Read JSON Access Token
try {
$global:token = (Get-Content $WPAccessToken | Out-String | ConvertFrom-Json -ErrorAction Stop).accessToken
Write-Host -NoNewLine "Access Token JSON File: "
Write-Host -ForegroundColor Green "OK, Read!"
}
catch {
#Handle exception when passed file is not JSON
Write-Host -ForegroundColor Red "Fatal Error when reading JSON file. Is it correctly formatted? {'accessToken' : 123xyz}"
exit;
}
#Read XLSX Export File
try {
#Read users from XLSX file
$global:xslxUsers = Import-Excel -Path $WPExportedUsers
Write-Host -NoNewLine "Workplace Users File: "
Write-Host -ForegroundColor Green "OK, Read!"
}
catch {
#Handle exception when unable to read file
Write-Host -ForegroundColor Red "Fatal Error when reading XLSX file. Is it the Workplace users export file?"
exit;
}
#Init Counters
$total = 0;
$updated = 0;
$skipped = 0;
$notapplicable = 0;
$errors = 0;
Foreach($u in $global:xslxUsers) {
#Get User Email from XLSX
$uemail = $u.Email
$unewemail = $u.NewEmail
$total++
#Check if is a standard email user and if email should be changed
if($uemail -And $unewemail) {
try {
#Get User via SCIM API
$results = Invoke-RestMethod -Uri ("https://www.facebook.com/scim/v1/Users/?filter=userName%20eq%20%22$uemail%22") -Headers @{Authorization = "Bearer " + $global:token}
If($results.Resources) {
#Get User params
$user = $results.Resources[0]
$uid = $user.id
$ouname = $user.userName
$askRes = ""
If($Interactive.IsPresent) {
Write-Host "[$uid/$ouname] -> [$unewemail]"
do {
Write-Host -ForegroundColor Blue -NoNewLine " * Confirm the change? (Press [Enter] to Continue, S/s to Skip): "
$askRes = Read-Host
} while (!(($askRes -eq "") -Or ($askRes -eq "S") -Or ($askRes -eq "s")))
} Else {
Write-Host -NoNewLine "[$uid/$ouname] -> [$unewemail]: "
}
if($askRes.length -eq 0) {
#Craft a Body
$body = (@{
schemas=@("urn:scim:schemas:core:1.0","urn:scim:schemas:extension:enterprise:1.0","urn:scim:schemas:extension:facebook:starttermdates:1.0","urn:scim:schemas:extension:facebook:accountstatusdetails:1.0","urn:scim:schemas:extension:facebook:auth_method:1.0");
id=$uid;
userName=$unewemail;
active=$true
} | ConvertTo-Json)
#Update User via SCIM API
$user = Invoke-RestMethod -Method PUT -URI ("https://www.facebook.com/scim/v1/Users/" + $uid) -Headers @{Authorization = "Bearer " + $global:token} -ContentType "application/json" -Body $body
#Print OK message
If($Interactive.IsPresent) {Write-Host -ForegroundColor Green " * OK, change reviewed by user and done!"}
Else {Write-Host -ForegroundColor Green "OK"}
$updated++
} elseif ($askRes -eq "S" -Or $askRes -eq "s") {
$skipped++;
Write-Host -ForegroundColor Blue " * User skipped as requested!"
}
} Else {
Write-Host -ForegroundColor Red "[$uemail] -> [$unewemail]: No user ($uemail) within your Workplace users."
$notapplicable++;
}
}
catch {
$errors++
# Dig into the exception and print error message
$status = $_.Exception.Response.StatusCode.value__
$err = $_.Exception.Response.StatusCode
$msg = ($_.ErrorDetails.Message | ConvertFrom-Json).Errors[0].description
If($Interactive.IsPresent) {
Write-Host -ForegroundColor Red " * KO ($status): $err - $msg"
} Else {
Write-Host -ForegroundColor Red "KO ($status): $err - $msg"
}
}
} Else {
$notapplicable++
}
}
Write-Host "---------------------------------------------------------------------------------------------------------"
Write-Host -NoNewLine -ForegroundColor Yellow "Summary "
Write-Host "- Total User: $total - Updated ($updated), Skipped ($skipped), Not Applicable/Found ($notapplicable), Errors ($errors)"
Write-Host "---------------------------------------------------------------------------------------------------------"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment