Home > Mobile >  How to download file that have inconsistent filename
How to download file that have inconsistent filename

Time:01-12

I'm downloading a file daily from SharePoint site and the code below is working fine. The only thing that I need to figure is how to pass in the filename parameter if the file name is inconsistent.

For example. The file was uploaded daily by someone like this

Full-Report-2023-01-10-03.00.13AM.csv

Full-Report-2023-01-09-02.00.43AM.csv

Full-Report-2023-01-08-20.30.53AM.csv

I'm supposed to download that file daily, but not sure how to do it if the time is included in the file name.

Any help or suggestion would be really appreciated.


function DownloadFile($token, $siteId, $driveId, $filePath, $fileName)
{
    $headers=@{}
    $headers.Add("Content-Type", "text/plain")
    $headers.Add("Authorization", "Bearer $token")
    $response = Invoke-WebRequest -Uri "https://graph.microsoft.com/v1.0/sites/$siteId/drives/$driveId/items/root:/$($filename):/content" -Method GET -OutFile $filePath -Headers $headers
}

# Need to fix here
DownloadFile -token $token -siteId $siteId -driveId $driveId -filePath "E:\Log-Files\Latest-Report.csv" -fileName "Full-Report-2023-01-08-20.30.53AM.csv" 

CodePudding user response:

me/drive/root/children endpoint doesn't support ordering by createdDateTime property, so you need to order files by name descending, use $filter to return only files that start with Full-Report- to reduce the number of file to be returned. You can use $select to return only id and name property. You can return only one item (by using $top) which should be the latest file.

$latestFiles = Invoke-WebRequest -Uri "https://graph.microsoft.com/v1.0/sites/$siteId/drives/$driveId/items/root/children?`$orderby=name desc&`$filter=startswith(name,'Full-Report-')&`$select=name,id&`$top=1" -Method GET -Headers $headers

So, if you have the following files

Full-Report-2023-01-10-03.00.13AM.csv
Full-Report-2023-01-09-02.00.43AM.csv
Full-Report-2023-01-08-20.30.53AM.csv

the query above should return only Full-Report-2023-01-10-03.00.13AM.csv

Parse the response json $latestFiles to get name property of the first item.

Now you can call DownloadFile and use name from the response above for -fileName

# parse the response json to get name property of the first item
$firstItem = $latestFiles[0] #parse response by yourself
DownloadFile -token $token -siteId $siteId -driveId $driveId -filePath "E:\Log-Files\Latest-Report.csv" -fileName $firstItem.Name
  • Related