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

未登录时Windows Server中PowerShell脚本任务计划执行失败求助

未登录Windows Server 2016时PowerShell脚本无法通过任务计划执行的排查求助

我正在排查Windows Server 2016中某PowerShell脚本的问题:脚本手动运行正常,但通过任务计划程序调度执行时,若未登录服务器则无法完成全部流程。

脚本核心功能:

  • 通过Flowroute REST API生成并获取通话报告
  • 下载报告压缩包,调用7-Zip解压至C:\Temp目录
  • 以应用注册授权方式调用Microsoft Graph API,将解压后的报告作为附件发送给指定收件人

我怀疑问题出在REST API或Microsoft Graph的调用环节,但无法准确定位。任务计划配置截图已提供,以下是完整脚本代码:

#Ensure that all TLS protocols are supported
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Ssl3
[Net.ServicePointManager]::SecurityProtocol = "Tls, Tls11, Tls12, Ssl3"



#Creates variables for the 1st of the month for last month and 1st of the month for current month.
$CurrentDate = Get-Date
$FirstDayOfCurrentMonth = Get-Date -Day 1 -Month $CurrentDate.Month -Year $CurrentDate.Year -Format "yyyy-MM-dd HH:mm:ss"
$FirstDayOfPreviousMonth = (Get-Date -Day 1 -Month ($CurrentDate.Month - 1) -Year $CurrentDate.Year).ToString("yyyy-MM-dd HH:mm:ss")
$DestNumber = "phone-number"


#Connects to Flowroute REST API with token created in flowroute.com uses variables from previous step
$BaseUrl = "https://" + "api.flowroute.com/v2/cdrs/exports/"
    $Headers = @{
        "Content-Type" = "application/vnd.api+json"
        "Authorization"  = "code"
    }

$body = @"
{
  `"data`": {
    `"type`": `"cdrexport"`,
    
    
    `"attributes"`: {

      `"filter_parameters"`: {
        `"start_call_start_time"`: `"$FirstDayOfPreviousMonth"`,
        `"start_call_end_time"`: `"$FirstDayOfCurrentMonth"`,
        `"destination_numbers"`: ["$DestNumber"]
      }
    }
  }
}
"@

#POSTS query to flowroute API to create report based on previous variables. 
    $response = Invoke-RestMethod $BaseUrl -Method "POST" -Headers $headers -Body $body

    $response | Get-member

    
     # Sleep to allow API to run
    Start-Sleep -Seconds 5

    # Based on documentation, endpoint to query is "/cdrs/exports/:cdrexport_id"
    # Gathering ID from previous query
    $URI = $BaseURL + $response.data.id
    $DateForFile = Get-Date -DisplayHint Date -Format "yyyy-MM-dd"

    # Status of your query via a GET request, no body needed
    $status = Invoke-RestMethod $URI -Method "GET" -Headers $headers

    # download URL
    $download_url = $status.data.attributes.download_url

    # Download the report created from POST query
    $output = "C:\Temp\Report-File${DateForFile}.csv.gz"
    Invoke-WebRequest -uri $download_url -outfile $output

    #Using 7zip extracts the downloaded file so it's not encrypted

& "C:\Program Files\7-zip\7z" x "C:\Temp\Report-file-${DateForFile}.csv.gz" -o"C:\Temp" -y


#Send the downloaded report to whoever the below Mailrecipient variable is set to


#Define Graph API variables from Azure App Registration
$clientID = "ID"
$Clientsecret = "Secret"
$tenantID = "ID"

#Define which mailbox to send from and recipient
$MailSender = "email"
$Mailrecipient = "email"
$CCRecipient1 = "email"
$CCRecipient2 = "email"

#Connect to GRAPH API
$tokenBody = @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    Client_Id     = $clientId
    Client_Secret = $clientSecret
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method POST -Body $tokenBody

$headers = @{
    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-type"  = "application/json"
}

#Locates the downloaded report to attach to email
$Attachment = "C:\Temp\report-file-${DateForFile}.csv"
#Get File Name and Base64 string
$FileName=(Get-Item -Path $Attachment).name
$base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($Attachment))


$MessageParams = @{
    "URI"         = "https://graph.microsoft.com/v1.0/users/$MailSender/sendMail"
    "Headers"     = $headers
    "Method"      = "POST"
    "ContentType" = 'application/json'
    "Body" = (@{
          "message" = @{
          "subject" = "Report"
          "body"    = @{
               "contentType" = 'HTML' 
               "content"     = "Email message."} 

          "toRecipients" = @(
          @{
          "emailAddress" = @{"address" = $Mailrecipient }
        } )

          "CCRecipients" = @(
          @{
          "emailAddress" = @{"address" = $CCrecipient1 }
        } 
        @{
          "emailAddress" = @{"address" = $CCrecipient2 }
        }
        
        )

        "attachments" = @(      
              @{      
                "@odata.type" = "#microsoft.graph.fileAttachment"
                "name" = $FileName
                "contentType" = "text/plain"
                "contentBytes" = "$base64string"          
                }        
        )
}
}) | ConvertTo-JSON -Depth 6
}
# Send the message
Invoke-RestMethod @Messageparams

#Deletes the downloaded report
(Get-ChildItem -File C:\Temp).Delete()

恳请提供排查思路,帮助实现脚本的无人值守自动化执行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:54:59