- t_o_dと申します。
- AzureADでのデバイス管理の際に、Graph APIを利用すると容易に情報を取得することができます。
- 今回はAzureADで名前(デバイス名)が重複しているデバイス一覧を取得する方法を記録いたします。
環境
- mac OS Monterey 13.0
- Google Apps Script
準備
- Graph API認証のため以下の値を公式サイトやこちらの記事を参考に取得してメモしておいてください。
- client_id : クライアントID
- client_secret : クライアントシークレット
- tennant_id : テナントID
手順
スクリプトエディタ起動
- Googleドライブを開き、新規で「Google Apps Script」を作成してスクリプトエディタを起動してください。
プロパティ設定
- スクリプトエディタを開いたら、スクリプトプロパティに準備でメモした内容を以下のように設定してください。
プロパティ | 値 |
---|---|
CLIENT_ID | 上記でメモしたクライアントID |
CLIENT_SECRET | 上記でメモしたクライアントシークレット |
TENNANT_ID | 上記でメモしたテナントID |
コード記述
- プロパティ設定後、以下の内容をスクリプトエディタの任意のgsファイルに記述。
const baseApi = 'https://graph.microsoft.com/v1.0'
const authApi = 'https://login.microsoftonline.com'
const properties = PropertiesService.getScriptProperties().getProperties()
function main(){
// トークン取得
const token = getToken();
const deviceNames = getDeviceNames(token)
const duplicateDevices = findDuplicates(deviceNames)
console.log(`重複数 : ${duplicateDevices.length}`)
console.log(duplicateDevices)
}
function getToken(){
// 認証情報
const clientId = properties.CLIENT_ID // クライアントID
const clientSecret = properties.CLIENT_SECRET // クライアントシークレット
const tennantId = properties.TENNANT_ID // テナントID
// トークン取得
try {
const res = UrlFetchApp.fetch(`${authApi}/${tennantId}/oauth2/v2.0/token`,{
method: 'post',
payload: {
'client_id': clientId,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': clientSecret,
'grant_type': 'client_credentials'
}
})
const json = JSON.parse(res.getContentText());
return json.access_token;
}catch(err){
throw new Error('トークン取得エラー');
}
}
// Azure上の全デバイス名の取得
function getDeviceNames(token){
const result = []
let link = `${baseApi}/devices?$top=999&$select=id,displayName`
do {
const res = UrlFetchApp.fetch(link, {
method: 'get',
headers: {
'Authorization': `Bearer ${token}`,
},
})
const json = JSON.parse(res.getContentText());
json.value.forEach(v => {
result.push(v.displayName)
})
link = json['@odata.nextLink'] ?? '';
} while(link)
return result;
}
// 配列から重複している値の抽出
function findDuplicates(targetArr){
if(!Array.isArray(targetArr)) throw new Error('引数には配列を指定してください。');
return targetArr.reduce((acc, v, i, arr) => {
if(arr.indexOf(v) !== i && !acc.includes(v)){
acc.push(v);
}
return acc;
}, [])
}
実行
- 修正後、main関数を実行してください。
- 実行ログに以下のようにAzureAD上で名前が重複している数とデバイスリストが出力されます。
- 出力の確認後、実際に重複しているかAzureデバイス管理画面で検索して2件以上出ることを確認します。
- 以上です。
まとめ
- 今後もMicrosoft Graphのさまざまなサービスを適宜利用していき、日々の業務改善に努めてまいります。
参考
アノテーション株式会社について
アノテーション株式会社は、クラスメソッド社のグループ企業として「オペレーション・エクセレンス」を担える企業を目指してチャレンジを続けています。「らしく働く、らしく生きる」のスローガンを掲げ、様々な背景をもつ多様なメンバーが自由度の高い働き方を通してお客様へサービスを提供し続けてきました。現在当社では一緒に会社を盛り上げていただけるメンバーを募集中です。少しでもご興味あれば、アノテーション株式会社WEBサイトをご覧ください。