How Can I Run a PowerShell Script Recursively in OneDrive?

0
28
Asked By TechieWizard42 On

I'm having trouble getting my PowerShell script to run through all the directories in OneDrive. It works perfectly when I run it in a local folder, but it only processes one level of folders in OneDrive. Here's a snippet of the script I think needs fixing:

```powershell
function GetFileHashes ([string] $rootLocation, [boolean] $isDirectory) {
if ($isDirectory) {
$hashList = Get-ChildItem -path $rootLocation -Recurse -Force -File | Get-FileHash
} else {
$hashList = Get-FileHash $rootLocation
}
return $hashList
}
```

I'd really appreciate any guidance on how to make this work recursively in OneDrive!

5 Answers

Answered By PnPPro22 On

I ended up writing my own recursive function using PnP to fetch the data directly. Something like this worked for me:

```powershell
Get-PnPFolderItem -FolderSiteRelativeUrl $newFolderURL -ItemType File
Get-PnPFolderItem -FolderSiteRelativeUrl $FolderURL -ItemType Folder
```
It’s a bit of an extra setup, but it can be effective!

Answered By CodeCrackerJack38 On

As someone else pointed out, the issue might be that you're trying to access shortcuts instead of actual files. I'd recommend using the OneDrive API or Power Automate to get the file hashes, which would bypass the issues with local syncing.

Answered By SkepticalSteve99 On

OneDrive often stores files as shortcuts unless you set them to be fully downloaded. Make sure to enable 'Always keep on this device' for the folder. I did that, and it allowed my script to access the subdirectories without issues. Otherwise, if the files aren’t fully downloaded, you’ll hit a wall when trying to get their hashes.

Answered By DataDude88 On

You could also look into the Graph API to retrieve file hashes directly, which would save you from doing the calculations manually. Here's the link: https://learn.microsoft.com/en-us/graph/api/resources/hashes?view=graph-rest-1.0.

Answered By PowerNerd23 On

If you simplify your function by removing the `$isDirectory` check, you could streamline your code. Here's a quick version that worked for me:

```powershell
function GetFileHashes ([string]$rootLocation) {
if ((Test-Path -LiteralPath $rootLocation -PathType Container -ErrorAction Stop)) {
$hashList = Get-ChildItem -Path $rootLocation -Recurse -Force -File | Get-FileHash
} elseif ((Test-Path -LiteralPath $rootLocation -PathType Leaf -ErrorAction Stop)) {
$hashList = Get-FileHash -LiteralPath $rootLocation
} else {
throw "Path not found: $rootLocation"
}
return $hashList
}
```
This version gets the hashes correctly across OneDrive for me.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.