LoginSignup
0
2

More than 5 years have passed since last update.

Office365の残ライセンスが少なくなったらSlackで通知

Last updated at Posted at 2017-06-29

Office365をこまめに少しづつ買っているので、残ライセンスを都度都度確認していたのですが、めんどくさくなったので、Powershellで自動化しました。(けっこう便利)
※初回だけ、認証情報を登録する必要があるので、手動で起動してください。

# 参考URL
# http://blog.kazuakix.jp/entry/2016/08/07/212916
# https://technet.microsoft.com/ja-jp/library/dn771773.aspx

# スクリプトが保存されているパスを取得。
$workDirectory = Split-Path -Parent ($MyInvocation.MyCommand.Path)
cd $workDirectory

$connectUserName = "hogecorp@hoge.ne.jp" # Azureの全体管理者のユーザ名
$credentialPasswordFile = "C:\\p.dat" # Azureの全体管理者のパスワードを保存するファイル

# パスワードファイルが無い時の処理。
# パスワード情報を保存したファイルが作成されます。
IF ( -Not(Test-Path $credentialPasswordFile) )
{
  $credential = Get-Credential
  $credential.Password | ConvertFrom-SecureString | Set-Content $credentialPasswordFile
}

# パスワードファイルから読みだして、$credentialに代入。
$credentialPassword = Get-Content $credentialPasswordFile | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential $connectUserName,$credentialPassword

# Office365に接続。
Connect-MSolService -Credential $credential

Get-MsolAccountSku | % {
  $licenseName = $_.AccountSkuId
  $remainingLincense = ($_.ActiveUnits - $_.ConsumedUnits)

  # 表示名を書き換えたいときはここで書き換える。
  $licenseName = $licenseName -replace "hogecorp:AAD_PREMIUM","*AzureAD_P1*"
  $licenseName = $licenseName -replace "hogecorp:SMB_BUSINESS","*O365_Business*"
  $licenseName = $licenseName -replace "hogecorp:POWER_BI_STANDARD","Power BI"

  # 30ライセンスを下回ったら通知。
  if ( $remainingLincense -le 30 ) {
    $remainingText += $licenseName + " が 残り" + $remainingLincense + " ライセンスだよ!"
    $remainingText += "`n"
  }  
}

# Slackに通知
# webhookのURLを入れてください。
$webhookURL = "https://hooks.slack.com/services/*******"
$messageText = $remainingText
$enc = [System.Text.Encoding]::GetEncoding('ISO-8859-1')
$utf8Bytes = [System.Text.Encoding]::UTF8.GetBytes($messageText)
$notificationPayload = @{ 
  text = $enc.GetString($utf8Bytes);
  username = "bot";
  icon_emoji = ":rage:"
}
Invoke-RestMethod -Uri $webhookURL -Method Post -Body (ConvertTo-Json $notificationPayload)
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2