-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCorrelation.updateAccount.ps1
96 lines (86 loc) · 3.64 KB
/
Correlation.updateAccount.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
## Correlate Account
## The purpose of this example script is to update the externalId(s)
## for a Google Suite User using a CSV. Please see ignoreExistingData flag
## it will overwrite any existing ExternalId's. The specific field set in
## the google admin is "Employee ID"
## Instructions
## 1. Update Settings
#Settings
$config = @{
clientId = "{GOOGLE CLIENT ID}";
clientSecret = "{GOOGLE CLIENT SECRET}";
redirectUri = "http://localhost/oauth2callback";
refreshToken = "{GOOGLE REFRESH TOKEN}";
ignoreExistingData = $false;
csvPath = "C:\temp\GoogleLink.csv"; # two columns: ID, userKey
}
#Import Data
$data = Import-Csv $config.csvPath;
#Authorization
$requestUri = "https://www.googleapis.com/oauth2/v4/token"
$refreshTokenParams = @{
client_id=$config.clientId;
client_secret=$config.clientSecret;
redirect_uri=$config.redirectUri;
refresh_token=$config.refreshToken;
grant_type="refresh_token"; # Fixed value
};
$response = Invoke-RestMethod -Method Post -Uri $requestUri -Body $refreshTokenParams -Verbose:$false
$accessToken = $response.access_token
#Add the authorization header to the request
$authorization = @{
Authorization = "Bearer $accesstoken";
'Content-Type' = "application/json";
Accept = "application/json";
}
#Process Users
$i=1;
foreach($item in $data)
{
Write-Verbose -Verbose "$($i):$($data.count)"
$body = $null;
if($config.ignoreExistingData -eq $true)
{
#Overwriting any existing externalId's
$body = @{ externalIds = @(
@{
value = "$($item.id)"
type = "organization";
}
)
}
}
else
{
#Retrieve Existing User
$parameters = @{
projection = "custom";
fields = "id,primaryEmail,externalIds";
}
$existingUser = Invoke-RestMethod -Uri "https://www.googleapis.com/admin/directory/v1/users/$($item.userKey)" -Body $parameters -Method GET -Headers $authorization
if($null -eq $existingUser.externalIds)
{
#No Existing externalIds, Only New ID
$body = @{ externalIds = @(
@{
value = "$($item.id)"
type = "organization";
}
)
}
}
else
{
#Setup New ID
$body = @{ externalIds = [System.Collections.ArrayList]@(@{ value = "$($item.id)"; type = "organization"; }) }
##Add Existing
foreach($extId in $existingUser.externalIds)
{
[void]$body.externalIds.Add($extId);
}
}
}
#Update User
$updatedUser = Invoke-RestMethod -Uri "https://www.googleapis.com/admin/directory/v1/users/$($item.userKey)" -Body ($body | ConvertTo-Json) -Method PUT -Headers $authorization
$i++;
}