How to ignore files recursively in Dropbox using Powershell

Viewed 250

I am a Node developer, and want to keep all my work saved in Dropbox except for the big 'node_modules' directories. I found a Powershell code that selectively ignores a folder existent in Dropbox in https://help.dropbox.com/files-folders/restore-delete/ignored-files:

Set-Content -Path 'C:\Users\yourname\Dropbox(Personal)\YourFileName.pdf' -Stream com.dropbox.ignored -Value 1

I want to create a Powershell script to help me find all 'node_modules' directories under Dropbox and then ignore them. I really need your help, because I really do not know much about Powershell.

Searching the Intenet, I wrote this little code snippet to recursively find all the 'node_modules' directories inside the Dropbox folder.

$BaseDir = "C:\Users\giann\Dropbox\IdeaProjects"
$NameToFind = "node_modules"
$MyVariable = Get-ChildItem $BaseDir -Recurse | Where-Object { $_.PSIsContainer -and $_.Name.EndsWith($NameToFind)}

My question is, how can I combine the two code snippets? Can you please point me in the right direction?

Thank you, your support is greatly appreciated.

1 Answers

Note: Set-Content requires the -Value parameter. If you just want to set the stream without changing the content, use -Value $null. It will not clear the contents of your file.

You're almost there, you just need to use your result from your Get-ChildItem command in the second block. You can also use the -Directory parameter on Get-ChildItem to enumerate only directories and not files:

$BaseDir = "C:\Users\giann\Dropbox\IdeaProjects"
$NameToFind = "node_modules"

# Changed variable name for clarity, multiline for readability
$FoundFiles = Get-ChildItem $BaseDir -Directory -Recurse | Where-Object {
  $_.Name.EndsWith($NameToFind)
}

foreach($file in $FoundFiles) { Set-Content -Path $file -Stream com.dropbox.ignored -Value $null }

Note: foreach can be used in place of ForEach-Object below but keep in mind the foreach used outside of the pipeline is a statement and functions differently than the foreach => ForeEach-Object cmdlet alias used inside of the pipeline. Read this article for more information on the differences between the foreach statement and ForEach-Object cmdlet.

If you don't care about using $FoundFiles later on, you can merge the last two expressions like so:

Get-ChildItem $BaseDir -Directory -Recurse | Where-Object {
  $_.Name.EndsWith($NameToFind)
} | ForEach-Object { Set-Content -Path $_ -Stream com.dropbox.ignored -Value $null }

For completeness and others who find this and want to know how to do the same on Linux, in case the Dropbox documentation moves the command to do this with Dropbox on Linux is:

xattr -w com.dropbox.ignored 1 "$filePath"

I'm not sure if Set-Content will set file attributes on Linux as xattr does, but the above is how Dropbox recommends doing it.

Related