admin管理员组

文章数量:1180415

I am trying to replace a colleague's PowerShell script that goes into an outlook email and downloads attachments, then saves them. This is what I currently have and it works when run manually but doesn't when done through task scheduler which is what I need since it needs to be automated. My colleague uses the ADAL library which doesn't get security updates.

if(!([System.Net.ServicePointManager]::SecurityProtocol.ToString().Contains("Tls12"))){
    $securityChanged = 1
    $oldProtocol= [System.Net.ServicePointManager]::SecurityProtocol
    [System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
}else{
    $securityChanged = 0
}
$ClientId = "cid"
$ClientSecret = "csecret"
$TenantId = "tid"
$mapping = Import-csv "path.csv"
# Calculate date (3 days ago)
$DaysAgo = (Get-Date).AddDays(-3).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
$logPath = "path\attachmentLog.txt"
$log = Get-content "path\attachmentLog.txt"

$TokenBody = @{
    client_id     = $ClientId
    scope         = "/.default"
    client_secret = $ClientSecret
    grant_type    = "client_credentials"
}

$TokenResponse = Invoke-RestMethod -Uri "/$TenantId/oauth2/v2.0/token" -Method Post -Body $TokenBody
$AccessToken = $TokenResponse.access_token
 
# API Endpoint
$Uri = ".0/users/$UserMailbox/mailFolders/$MailFolder/messages?`$top=50&`$filter=hasAttachments eq true and receivedDateTime ge $DaysAgo"

$MailFolder = "Inbox"
$UserMailbox = "[email protected]"

# Get messages with attachments
# Fetch the email
try{
$Responses = Invoke-RestMethod -Uri $Uri -Headers @{ Authorization = "Bearer $AccessToken" } -Method Get
}catch{
#email function
    return
}
foreach ($Response in $Responses.value) {
    #return
    Write-Host "Processing Email: $($Response.subject)"
    Write-Host "Received Date: $($Response.receivedDateTime)"
    # Get the message ID
    $MessageId = $Response.id
    $email = $Response.sender.emailAddress[0].address
    
    foreach($map in $mapping){
        $domain = $map.Incoming.ToLower()
        if($email.ToLower().Contains($domain)){
            $DownloadPath = $map.Destination+"\"
            $fileType = $map.File
            break
        }
    }
    # Get attachments for the email
    $AttachmentsUri = ".0/users/$UserMailbox/messages/$MessageId/attachments"
    $AttachmentsResponse = Invoke-RestMethod -Uri $AttachmentsUri -Headers @{ Authorization = "Bearer $AccessToken" } -Method Get
    
    # Process each attachment
    foreach ($Attachment in $AttachmentsResponse.value) {
        $FileName = $Attachment.Name
        $pattern = $fileType -replace '\*', '.*'
        if(!($FileName -match $pattern)){
            Write-Host ("Email: ", $Response.subject, " contains non matching attachment")
            continue
        }

        # Check if it's a file attachment
        if ($Attachment.'@odata.type' -eq "#microsoft.graph.fileAttachment") {
             
            $FileContent = [System.Convert]::FromBase64String($Attachment.ContentBytes)

            $FilePath = Join-Path -Path $DownloadPath -ChildPath $FileName
            if($log.IndexOf($FilePath) -ne -1){
                Write-Output "File already exists"
                continue
            }else{
                Write-Output "File doesn't already exists"
            }
            #continue
            Write-Output $FilePath | Out-File $logPath -Encoding utf8 -Append
            # Save the attachment
            [System.IO.File]::WriteAllBytes($FilePath, $FileContent)
            Write-Host "Attachment saved: $FilePath"
        } else {
            Write-Host "Skipping non-file attachment: $FileName"
        }
    }
}

When doing it through task scheduler, I had the $TokenResponse.access_token sent to a logfile to see what was going on, and after decoding it got:

  • "aud":";
  • "roles":["Mail.Read"]

apparently the fact that roles is here instead of scp is significant. On the Azure Portal, I have:

  • Microsoft Graph: Mail.Read
  • Type: Delegated
  • Description: Read user mail
  • Admin consent not required

So can anyone identify why it doesn't work through task scheduler and potential fixes?

本文标签: