1
| Connect-AzAccount -Environment AzureChinaCloud
|
1
| Connect-AzAccount -EnvironmentName azurechinacloud -Identity
|
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
| $appId = "ad43de94-a2a1-xxxxxxxx"# 指定应用的对象ID
$daysBeforeExpiryStartSending = 30 # 提前多少天开始发送提醒
$smtpServer = "smtp.qq.com" # SMTP服务器地址
$smtpPort = 587 # SMTP端口
$smtpUser = "[email protected]" # 你的电子邮件地址
$smtpPassword = "" # 你的SMTP应用密码
$smtpFrom = "[email protected]" # 发件人邮箱
$smtpTo = "[email protected]" # 收件人邮箱
# 获取当前时间
$currentDate = Get-Date
# 获取指定的应用程序
$app = Get-AzADApplication -ObjectId $appId
if ($app) {
# 获取应用程序的所有凭据
$credentials = Get-AzADAppCredential -ObjectId $appId
foreach ($credential in $credentials) {
# 计算剩余天数
$expiryDate = [datetime]::Parse($credential.EndDateTime)
$daysRemaining = ($expiryDate - $currentDate).Days
# 如果密码将在接下来的30天内到期或已经过期
if ($daysRemaining -le $daysBeforeExpiryStartSending -or $daysRemaining -lt 0) {
# 构建邮件内容
$subject = "Azure AppReg Credential Expiry Reminder"
$body = @"
Dear Administrator,
The credential with Key ID '{0}' for the application with object ID '{1}' (Name: {2}) will expire or has expired.
There are {3} days remaining until the expiration date, which is on {4}.
Please update the credential to avoid any disruptions.
Best regards,
Your Azure Team.
"@ -f $credential.KeyId, $appId, $app.DisplayName, [math]::Max($daysRemaining, 0), $expiryDate.ToString("yyyy-MM-dd")
# 创建SMTP客户端凭据
$securePassword = ConvertTo-SecureString $smtpPassword -AsPlainText -Force
$smtpCredential = New-Object System.Management.Automation.PSCredential ($smtpUser, $securePassword)
# 创建SmtpClient实例,并设置超时时间
$smtpClient = New-Object Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtpClient.EnableSsl = $true
$smtpClient.DeliveryMethod = [Net.Mail.SmtpDeliveryMethod]::Network
$smtpClient.UseDefaultCredentials = $false
$smtpClient.Credentials = $smtpCredential
$smtpClient.Timeout = 300000 # 设置超时时间为5分钟(300秒)
# 添加调试输出
Write-Host "Connecting to SMTP server..."
try {
# 创建一个邮件消息对象
$message = New-Object Net.Mail.MailMessage($smtpFrom, $smtpTo, $subject, $body)
$message.IsBodyHtml = $false
$message.Priority = [Net.Mail.MailPriority]::High
# 发送邮件
$smtpClient.Send($message)
Write-Host "Email sent successfully."
} catch {
Write-Host "Failed to send email: $_"
Write-Host "SMTP Server Error Details:"
Write-Host $_.Exception.Message
}
}
}
} else {
Write-Host "Application with object ID '$appId' not found."
}
|