I wrote a script to delete old files from a network drive, and it worked well until I hit the 260 character limit, which I solved by installing NTFSSecurity. However, I've hit a snag with Get-ChildItem2: it scans through the '~snapshot' directory, which I'd like it to ignore, just like it does for other excluded folders like 'AUDIT' and '2025'. Despite my efforts to add '~snapshot' to the exclusion list, the script doesn't recognize it and still processes these snapshots, causing hours of errors due to access denials. Any thoughts on why this is happening and how to fix it?
4 Answers
It looks like your issue might stem from how you’re using the quotes. You're using double quotes for '`~snapshot`', which could cause problems because it resembles a system variable. Try using single quotes instead, like this: `'~snapshot'`. This should fix the issue and allow your script to exclude it as intended. Also, consider stepping through the script to better pinpoint where things are going wrong. Using a `foreach` instead of `ForEach-Object` might simplify your code too!
Good tip! Tilde expands differently in double quotes.
Instead of handling it the way you've been doing, try this approach to print out what is being processed:
Get-ChildItem2 -Path $TargetDrive -Recurse -File | ForEach-Object {
Write-Host $_.DirectoryName.Substring($TargetDrive.Length).TrimStart('')
}
This will help you see how the tilde is being treated in your paths. Just a hunch, but it’s possible that PowerShell is interpreting the tilde as the user’s home directory.
You might want to add some breakpoints or debug statements to see the variable values at various points in your script. This might give you a clearer idea of what's really happening when it's executing.
Just a heads up, the '~snapshot' directory on many mapped drives corresponds to NetApp filer volumes, which store snapshots. These snapshots are read-only on your mapped drive and you can't delete them here. Ideally, you manage these directly from the filer, possibly via REST calls in PowerShell or other methods. If you need to delete or manage them, you’ll require the necessary credentials to access the filer.

Yeah, definitely stick with single quotes for static strings!