导出其机密和证书超出所需日期的应用Export apps with secrets and certificates expiring beyond the required date

此 PowerShell 脚本示例以非交互方式将目录中指定应用所需的期限后过期的所有应用注册机密和证书导出到 CSV 文件。This PowerShell script example exports all app registrations secrets and certificates expiring beyond a required period for the specified apps from your directory in a CSV file non-interactively.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

示例脚本Sample script

#################################################################################
#DISCLAIMER: This is not an official PowerShell Script. We designed it specifically for the situation you have encountered right now.
#Please do not modify or change any preset parameters. 
#Please note that we will not be able to support the script if it is changed or altered in any way or used in a different situation for other means.

#This code-sample is provided "AS IT IS" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.
#This sample is not supported under any Microsoft standard support program or service.. 
#Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. 
#The entire risk arising out of the use or performance of the sample and documentation remains with you. 
#In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the script be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of  the use of or inability to use the sample or documentation, even if Microsoft has been advised of the possibility of such damages.
#################################################################################

$loginURL = "https://login.partner.microsoftonline.cn"
$resource = "https://microsoftgraph.chinacloudapi.cn"

#PARAMETERS TO CHANGE
$ClientID = "App ID"
$ClientSecret = "APP Secret"
$TenantName = "TENANT.partner.onmschina.cn"

$Months = "Number of months"
$Path = "add a path here\File.csv"
###################################################################
#Repeating Function to get an Access Token based on the parameters:
function RefreshToken($loginURL, $ClientID, $clientSecret, $tenantName) { 
    $body = @{grant_type = "client_credentials"; client_id = $ClientID; client_secret = $ClientSecret; scope = "https://microsoftgraph.chinacloudapi.cn/.default" } 
    $oauthResponse = Invoke-RestMethod -Method POST -Uri $loginURL/$TenantName/oauth2/v2.0/token -Body $body 
    return $oauthResponse
}

#BUILD THE ACCESS TOKEN
$oauth = RefreshToken -loginURL $loginURL -resource $resource -ClientID $ClientID -clientSecret $ClientSecret -tenantName $TenantName
$Identity = $oauth.access_token

##############################################

$headerParams = @{'Authorization' = "$($oauth.token_type) $($Identity)" }
$AppsSecrets = "https://microsoftgraph.chinacloudapi.cn/v1.0/applications"

$ApplicationsList = (Invoke-WebRequest -Headers $headerParams -Uri $AppsSecrets -Method GET)
$Logs = @()
$NextCounter = 0

do {
    foreach ($event in ($ApplicationsList.Content | ConvertFrom-Json | select -ExpandProperty value)) { 
        $ids = $event.id
        $AppName = $event.displayName
        $AppID = $event.appId
        $secrets = $event.passwordCredentials
        $NextCounter++

        foreach ($s in $secrets) {
            $StartDate = $s.startDateTime
            $EndDate = $s.endDateTime
            $pos = $StartDate.IndexOf("T")
            $leftPart = $StartDate.Substring(0, $pos)
            $position = $EndDate.IndexOf("T")
            $leftPartEnd = $EndDate.Substring(0, $pos)
            $DatestringStart = [Datetime]::ParseExact($leftPart, 'yyyy-MM-dd', $null)
            $DatestringEnd = [Datetime]::ParseExact($leftPartEnd, 'yyyy-MM-dd', $null)
            $OptimalDate = $DatestringStart.AddMonths($Months)

            if ($OptimalDate -lt $DatestringEnd) {
                $Log = New-Object System.Object
                $Log | Add-Member -MemberType NoteProperty -Name "Application" -Value $AppName
                $Log | Add-Member -MemberType NoteProperty -Name  "AppID" -value $AppID
                $Log | Add-Member -MemberType NoteProperty -Name "Secret Start Date" -Value $DatestringStart
                $Log | Add-Member -MemberType NoteProperty -Name  "Secret End Date" -value $DatestringEnd

                $Owners = "https://microsoftgraph.chinacloudapi.cn/v1.0/applications/$ids/owners"
                $ApplicationsOwners = (Invoke-WebRequest -Headers $headerParams -Uri $Owners -Method GET)

                foreach ($user in ($ApplicationsOwners.Content | ConvertFrom-Json | select -ExpandProperty value)) {
                    $Owner = $user.displayname
                    $Log | Add-Member -MemberType NoteProperty -Name  "AppOwner" -value $Owner
                }
                $Logs += $Log
            }
        }

        If ($NextCounter -eq 100) {
            $odata = $ApplicationsList.Content | ConvertFrom-Json
            $AppsSecrets = $odata.'@odata.nextLink'
            try {
                $ApplicationsList = Invoke-WebRequest -UseBasicParsing -Headers $headerParams -Uri $AppsSecrets -Method Get -ContentType "application/Json"
            }
            catch {
                $_
            }

            $NextCounter = 0
            sleep 1
        }
    }

} while ($AppsSecrets -ne $null)

$Logs | Export-CSV $Path -NoTypeInformation -Encoding UTF8

脚本说明Script explanation

此脚本以非交互方式工作。This script is working non-interactively. 使用此脚本的管理员需要使用自己的应用 ID、应用程序机密、租户名称、应用凭据到期期限以及用于导出 CSV 的路径来更改“#PARAMETERS TO CHANGE”节中的值。The admin using it will need to change the values in the "#PARAMETERS TO CHANGE" section with their own App ID, Application Secret, Tenant Name, the period for the apps credentials expiration and the Path where the CSV will be exported. 此脚本使用 Client_Credential Oauth 流。函数“RefreshToken”将基于管理员修改的参数值来生成访问令牌。This script uses the Client_Credential Oauth Flow The function "RefreshToken" will build the access token based on the values of the parameters modified by the admin.

“Add-Member”命令负责在 CSV 文件中创建列。The "Add-Member" command is responsible for creating the columns in the CSV file.

命令Command 说明Notes
Invoke-WebRequestInvoke-WebRequest 将 HTTP 和 HTTPS 请求发送到网页或 Web 服务。Sends HTTP and HTTPS requests to a web page or web service. 它将分析响应并返回链接、图像和其他重要 HTML 元素的集合。It parses the response and returns collections of links, images, and other significant HTML elements.

后续步骤Next steps

要详细了解 Azure AD PowerShell 模块,请参阅 Azure AD PowerShell 模块概述For more information on the Azure AD PowerShell module, see Azure AD PowerShell module overview.

有关应用程序管理的其他 PowerShell 示例,请参阅应用程序管理的 Azure AD PowerShell 示例For other PowerShell examples for Application Management, see Azure AD PowerShell examples for Application Management.