Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 54 additions & 10 deletions apps/filesync.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
# Same file = same name, size and SHA-256 in any folder; contents are read only for name and size matches
# Only Replace, Sync and Duplicates change existing files, always after listing them and asking
# Duplicates uses the Recycle Bin; network and mapped drives have none, so it asks you to type yes
# A path too long for the Recycle Bin is moved to <folder>\~filesync-bin first, then recycled
# Works with OneDrive and SharePoint (online-only files download), network drives, paths over 260 chars
# Before a change the first 10 files are shown; v at the y/n/v prompt shows all
# Folders are kept only while the window is open (fine on a shared PC). No admin, no downloads
Expand Down Expand Up @@ -306,6 +307,12 @@ public static class LongPath {
static extern bool CreateDirectoryW(string path, IntPtr sa);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern uint GetFileAttributesW(string path);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool DeleteFileW(string path);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool RemoveDirectoryW(string path);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool MoveFileExW(string src, string dst, uint flags);
static string P(string path) {
if (path.StartsWith(@"\\?\")) return path;
if (path.StartsWith(@"\\")) return @"\\?\UNC\" + path.Substring(2);
Expand All @@ -320,6 +327,9 @@ public static class LongPath {
public static bool FileExists(string path) { uint a = GetFileAttributesW(P(path)); return a != 0xFFFFFFFFu && (a & 0x10u) == 0; }
public static bool DirExists(string path) { uint a = GetFileAttributesW(P(path)); return a != 0xFFFFFFFFu && (a & 0x10u) != 0; }
public static void Copy(string src, string dst, bool overwrite) { if (!CopyFileW(P(src), P(dst), !overwrite)) throw Err(); }
public static void Delete(string path) { if (!DeleteFileW(P(path))) throw Err(); }
public static void RemoveDirectory(string path) { if (!RemoveDirectoryW(P(path))) throw Err(); }
public static void Move(string src, string dst) { if (!MoveFileExW(P(src), P(dst), 0)) throw Err(); }
public static void CreateDirectory(string path) {
path = path.TrimEnd('\\');
if (path.Length <= 3 || DirExists(path)) return;
Expand All @@ -344,6 +354,15 @@ function New-Folder([string]$path) {
function Copy-File([string]$src, [string]$dst, [bool]$overwrite) {
if ($LongPaths) { [LongPath]::Copy($src, $dst, $overwrite) } else { [IO.File]::Copy($src, $dst, $overwrite) }
}
function Remove-File([string]$path) {
if ($LongPaths) { [LongPath]::Delete($path) } else { [IO.File]::Delete($path) }
}
function Remove-Folder([string]$path) {
if ($LongPaths) { [LongPath]::RemoveDirectory($path) } else { [IO.Directory]::Delete($path) }
}
function Move-File([string]$src, [string]$dst) {
if ($LongPaths) { [LongPath]::Move($src, $dst) } else { [IO.File]::Move($src, $dst) }
}
# Folder part of a path without the .NET length check
function Get-ParentPath([string]$path) { $path.Substring(0, $path.LastIndexOf('\')) }

Expand Down Expand Up @@ -707,11 +726,30 @@ function Test-RecycleBin([string]$folder) {
try { return ((New-Object IO.DriveInfo $root).DriveType -ne 'Network') } catch { return $false }
}

# Delete through the Windows shell: the only route that behaves on OneDrive folders
function Remove-ToBin([string]$path, [bool]$bin, [bool]$folder = $false) {
$how = if ($bin) { 'SendToRecycleBin' } else { 'DeletePermanently' }
if ($folder) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($path, 'OnlyErrorDialogs', $how) }
else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($path, 'OnlyErrorDialogs', $how) }
# Delete through the Windows shell: the only route that behaves on OneDrive folders.
# The shell cannot take paths over 260 characters, so such a file is first moved (same
# drive, so instant) to a short name under $Holding and recycled from there; an empty
# folder that long is simply removed. $Holding is $null when deleting permanently.
function Remove-ToBin([string]$path, [bool]$bin, [bool]$folder = $false, [string]$Holding = $null) {
if (-not $bin) {
if ($folder) { Remove-Folder $path } else { Remove-File $path }
return
}
if ($folder) {
if ($path.Length -gt 247) { Remove-Folder $path }
else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($path, 'OnlyErrorDialogs', 'SendToRecycleBin') }
return
}
if ($path.Length -gt 259 -and $Holding) {
New-Folder $Holding
$leaf = $path.Substring($path.LastIndexOf('\') + 1)
$script:HoldingN++
$short = "$Holding\$script:HoldingN-$leaf"
if ($short.Length -gt 259) { $short = $short.Substring(0, 259) }
Move-File $path $short
$path = $short
}
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($path, 'OnlyErrorDialogs', 'SendToRecycleBin')
}

function Invoke-Duplicates([string]$Which) {
Expand Down Expand Up @@ -775,15 +813,17 @@ function Invoke-Duplicates([string]$Which) {
}

Add-Type -AssemblyName Microsoft.VisualBasic
$holding = if ($bin) { "$root\~filesync-bin" } else { $null }
$script:HoldingN = 0
$done = 0; $n = 0
$failed = New-Object System.Collections.Generic.List[string]
$dirs = @{}
foreach ($d in $todo) {
$n++
try {
Say " [$n/$($todo.Count)] $($d.Rel)" 'DarkGray'
Remove-ToBin $d.File.FullName $bin
$dirs[$d.File.DirectoryName] = $true
Remove-ToBin $d.File.FullName $bin $false $holding
$dirs[(Get-ParentPath $d.File.FullName)] = $true
$done++
} catch {
$failed.Add("$($d.Rel): $($_.Exception.Message)")
Expand All @@ -795,16 +835,20 @@ function Invoke-Duplicates([string]$Which) {
$cur = $dir
while ($cur.Length -gt $root.Length -and $cur.StartsWith($root, [StringComparison]::OrdinalIgnoreCase)) {
try {
if (-not [IO.Directory]::Exists($cur)) { break }
if (@([IO.Directory]::EnumerateFileSystemEntries($cur) | Select-Object -First 1).Count) { break }
if (-not (Test-PathQuiet $cur 'Container')) { break }
if (@(Get-ChildItem -LiteralPath $cur -Force -ErrorAction Stop).Count) { break }
Remove-ToBin $cur $bin $true
$removed++
} catch { break }
$cur = [IO.Path]::GetDirectoryName($cur)
$cur = Get-ParentPath $cur
}
}
if ($holding -and (Test-PathQuiet $holding 'Container')) {
try { if (-not @(Get-ChildItem -LiteralPath $holding -Force -ErrorAction Stop).Count) { Remove-Folder $holding } } catch {}
}
$where = if ($bin) { 'sent to the Recycle Bin' } else { 'deleted' }
Say " DONE - $done of $($todo.Count) $where$(if ($removed) { ", $removed empty folder(s) removed" })" $(if ($failed.Count) { 'Yellow' } else { 'Green' })
if ($script:HoldingN) { Say " $script:HoldingN file(s) had paths too long for the Recycle Bin, so they were moved to $holding first; restoring them puts them back there." 'Yellow' }
Show-Errors $failed
}

Expand Down
Loading