You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何运行执行时长超1小时的计划PowerShell Azure Function?

问题:能否运行执行时长超1小时的计划PowerShell Azure Function?

已尝试消费计划(Consumption Plan)和高级计划(Premium Plan),但计划任务因超时卡住。

补充说明

需要获取Azure Active Directory(AAD)中的所有组成员,调用了Microsoft Graph接口https://graph.microsoft.com/v1.0/groups?$top=999&$expand=members。由于组成员数量超过999,需使用分页功能,对应的PowerShell代码片段如下:

$allPages = @()
$items = (Invoke-RestMethod -Method 'Get' -Uri 'https://graph.microsoft.com/v1.0/groups?$top=999&$expand=members' -Headers $authHeader  -ContentType 'Application/Json') 
$allPages += $items.value

$index = 0
if ($items.'@odata.nextLink') {
        do {
              $index++
              "Index counter: $index"

              $token = (Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com/").Token
              $authHeader = @{Authorization = "Bearer $token"}

              $items = (Invoke-RestMethod -Method 'Get' -Uri $items.'@odata.nextLink' -Headers $authHeader  -ContentType 'Application/Json')
              $allPages += $items.value
         } until (
             !$items.'@odata.nextLink'
         )
}

$items = $allPages
"Count items: " + $items.Count

$filePath = "D:\home\data\$($fileName)"

Write-Host "Convert to csv to path '$($filePath)'" -ForegroundColor green
$items | Export-Csv -NoTypeInformation -Path $filePath

解决方案

1. 针对Azure Function执行时长限制的处理

  • 消费计划:最大执行时长固定为10分钟,无法调整,完全不适合1小时以上的任务。
  • 高级计划:默认最大执行时长60分钟,可手动调整至最长300分钟(5小时)。操作路径:进入Azure Function应用的「配置」→「常规设置」,找到「函数超时」选项修改时长。
  • 专用(App Service)计划:无执行时长限制,是超长时间任务的最佳选择,可根据负载需求选择对应规格的虚拟机。

2. 优化AAD组成员获取代码

当前代码存在效率问题,可从以下几点优化:

  • 减少Token获取次数:每次分页都调用Get-AzAccessToken会增加额外开销,建议初始化时获取一次Token,仅在Token即将过期时重新获取。
  • 使用Microsoft Graph PowerShell模块:模块内置分页逻辑,无需手动处理@odata.nextLink,代码更简洁高效:
# 首次运行需安装模块:Install-Module Microsoft.Graph.Groups -Force -AllowClobber
Import-Module Microsoft.Graph.Groups

# 获取所有组及成员,自动处理分页
$allGroups = Get-MgGroup -All $true -ExpandProperty members
$allPages = $allGroups | Select-Object Id, DisplayName, @{Name='Members'; Expression={$_.Members}}

# 导出到CSV
$filePath = "D:\home\data\$fileName"
$allPages | Export-Csv -NoTypeInformation -Path $filePath
  • 分批导出数据:若数据量极大,可分批将数据写入CSV,避免一次性加载所有数据到内存导致性能下降。

内容的提问来源于stack exchange,提问作者KEM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 22:45:27