Scheduled Task for PowerShell Only Exports One Row

Yes, I’m using the same script that I run manually which returns the correct amount of records. I’m running it with my account which is a local admin.

I’d think that if it was a permission issue, a file wouldn’t be written at all? That’s why I’m unsure why it would write the file and insert one record.

Below is the script I’m running:

Start-Transcript -Path "C:\PowerShell\output\transcript.txt" -NoClobber -Append
Disconnect-AzAccount
Import-Module AZ

$dashLine = "----------------------------------------------------------------------------------------"

Write-Host "Remote PowerShell Session"
Write-Host $dashLine

#region
#--------------------------------------------------------------------------
# Set up 'Connection Object' for Remote PoSh Session
$username = ''
$password = Get-Content "C:\PowerShell\key\tenantName.key" | ConvertTo-SecureString
$oLiveCred = New-Object System.Management.Automation.PSCredential $username, $password
#--------------------------------------------------------------------------
#endregion

#region
#--------------------------------------------------------------------------
# Remote PoSh Session attach
Write-Host "Creating Remote PowerShell Session connection..."
$session = New-PSSession -ConfigurationName Microsoft.Exchange -Authentication Basic -ConnectionUri https://ps.com -AllowRedirection:$true -Credential $oLiveCred
Import-PSSession $session -AllowClobber
#--------------------------------------------------------------------------
#endregion

#region
#--------------------------------------------------------------------------
# Declare variables
$startDate = (Get-Date).AddDays(-1)
$endDate = (Get-Date)
$scriptStart = (Get-Date)
$sessionName = (Get-Date -Format 'u') + 'pbiauditlog'
#--------------------------------------------------------------------------

# Reset User Audit Accumulator
$aggregateResults = @()
# Loop Counter
$i = 0
Do {
    $currentResults = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -SessionId $sessionName -SessionCommand ReturnLargeSet -ResultSize 1000 -RecordType PowerBi 
    if ($currentResults.Count -gt 0) {
        Write-Host ("Finished {3} search #{1}, {2} records: {0} minutes." -f [math]::Round((New-TimeSpan -Start $scriptStart).TotalMinutes,4), $i, $currentResults.Count, $username.UserPrincipalName )
        # Accumulate Data
        $aggregateResults += $currentResults
        # No need to do another query if the # of records returned are <1k
        if ($currentResults.Count -lt 1000){
            $currentResults = @()
        } else {
            $i++
        }
        }
    } Until ($currentResults.Count -eq 0) # --- End of Session Search Loop --- #         

$data = @()
    foreach ($auditLogItem in $aggregateResults){
        $datum = New-Object -TypeName PSObject 
        $d = ConvertFrom-Json $auditLogItem.AuditData
        $datum | Add-Member -MemberType NoteProperty -Name CreationTime -Value $auditlogitem.CreationDate
        $datum | Add-Member -MemberType NoteProperty -Name Operation -Value $d.Operation
        $datum | Add-Member -MemberType NoteProperty -Name Workload -Value $d.Workload
        $datum | Add-Member -MemberType NoteProperty -Name UserId -Value $d.UserId
        $datum | Add-Member -MemberType NoteProperty -Name Activity -Value $d.Activity
        $datum | Add-Member -MemberType NoteProperty -Name Item -Value $d.ItemName
        $datum | Add-Member -MemberType NoteProperty -Name WorkSpaceName -Value $d.WorkSpaceName
        $datum | Add-Member -MemberType NoteProperty -Name DashboardName -Value $d.DashboardName
        $datum | Add-Member -MemberType NoteProperty -Name DatasetName -Value $d.DatasetName
        $datum | Add-Member -MemberType NoteProperty -Name ReportName -Value $d.ReportName
        $datum | Add-Member -MemberType NoteProperty -Name ObjectId -Value $d.ObjectId
    

    foreach ($dataset in $d.$datasets){
        $datum.DatasetName = $dataset.DatasetName
        $datum.DatasetId = $dataset.DatasetId
    }
    $data += $datum
    }

#region
#--------------------------------------------------------------------------
# Build File and Output to Path
$dateString = $startDate.ToString("yyyyMMdd")
$fileName = ("C:\PowerShell\output\" + $dateString + ".csv")
# Remove Column Header and Input Data
#$data | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Export-Csv -Path $fileName
$data | Select-Object -Skip 1 | Export-Csv -NoTypeInformation -Path $fileName
Remove-PSSession -Id $session.Id
#--------------------------------------------------------------------------
#endregion

Stop-Transcript