437 lines
25 KiB
PowerShell
437 lines
25 KiB
PowerShell
#Requires -Version 5.1
|
|||
|
|
<#
|
||
|
|
.SYNOPSIS
|
||
|
|
Previews or shortens filenames in Documents, Pictures, and Desktop for OneDrive.
|
||
|
|
.DESCRIPTION
|
||
|
|
Preview is the default. The RMM supplies individual variables inherited by the
|
||
|
|
core script. Standalone -Options and legacy OneDrivePrepOptions are also supported.
|
||
|
|
See docs/OneDrive-PathPreparation.md for variable names and defaults.
|
||
|
|
Only filenames are renamed, in place; extensions and file contents are preserved.
|
||
|
|
Folders that need restructuring are reported. Does not enable OneDrive backup.
|
||
|
|
.EXAMPLE
|
||
|
|
.\Repair-OneDriveKnownFolderPaths.ps1 -Options @{ OneDriveRoot='C:\Users\Jane\OneDrive - Contoso' }
|
||
|
|
.EXAMPLE
|
||
|
|
.\Repair-OneDriveKnownFolderPaths.ps1 -Options @{ UserProfilePath='C:\Users\Jane'; OneDriveRoot='C:\Users\Jane\OneDrive - Contoso'; Apply=$true }
|
||
|
|
#>
|
||
|
|
[CmdletBinding(SupportsShouldProcess=$true, PositionalBinding=$false)]
|
||
|
|
param(
|
||
|
|
# Some Tools.ps1 versions pass an empty positional string to live scripts.
|
||
|
|
[Parameter(Position=0, DontShow=$true)]
|
||
|
|
[AllowEmptyString()][ValidatePattern('^\s*$')][string]$RmmArgument,
|
||
|
|
[hashtable]$Options
|
||
|
|
)
|
||
|
|
|
||
|
|
# Keep implementation variables/preferences local when Run-Script dot-sources us.
|
||
|
|
& {
|
||
|
|
param($Configuration, $Caller)
|
||
|
|
Set-StrictMode -Version 2.0
|
||
|
|
$ErrorActionPreference = 'Stop'
|
||
|
|
if ($null -eq $Configuration) {
|
||
|
|
# Like the Office installer, capture the RMM's injected strings without
|
||
|
|
# assigning to those variables or requiring a caller-built hashtable.
|
||
|
|
$rmmInputs = @{}
|
||
|
|
foreach ($inputName in @('UserProfilePath','OneDriveRoot','Apply','MaxPathLength','MaxNameLength','ReportDirectory','DocumentsPath','PicturesPath','DesktopPath')) {
|
||
|
|
$inputVariable = Get-Variable -Name $inputName -ErrorAction SilentlyContinue
|
||
|
|
if ($null -ne $inputVariable) { $rmmInputs[$inputName] = ([string]$inputVariable.Value).Trim() }
|
||
|
|
}
|
||
|
|
if ($rmmInputs.Count) {
|
||
|
|
$Configuration = @{}
|
||
|
|
foreach ($inputName in @('UserProfilePath','OneDriveRoot','Apply','MaxPathLength','MaxNameLength','ReportDirectory')) {
|
||
|
|
if ($rmmInputs[$inputName]) { $Configuration[$inputName] = $rmmInputs[$inputName] }
|
||
|
|
}
|
||
|
|
$explicitFolders = @{}
|
||
|
|
foreach ($folderName in @('Documents','Pictures','Desktop')) {
|
||
|
|
$folderValue = $rmmInputs[$folderName + 'Path']
|
||
|
|
if ($folderValue -and $folderValue -ine 'Auto') { $explicitFolders[$folderName] = $folderValue }
|
||
|
|
}
|
||
|
|
if ($explicitFolders.Count -gt 0 -and $explicitFolders.Count -ne 3) {
|
||
|
|
throw 'Supply DocumentsPath, PicturesPath, and DesktopPath together, or leave all three Auto/blank for registry discovery.'
|
||
|
|
}
|
||
|
|
if ($explicitFolders.Count -eq 3) { $Configuration.KnownFolderPaths = $explicitFolders }
|
||
|
|
} else {
|
||
|
|
$shared = Get-Variable -Name OneDrivePrepOptions -ErrorAction SilentlyContinue
|
||
|
|
$Configuration = if ($shared) { $shared.Value } else { @{} }
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if ($Configuration -isnot [hashtable]) { throw 'Options / OneDrivePrepOptions must be a hashtable.' }
|
||
|
|
$settings = @{
|
||
|
|
UserProfilePath=''; OneDriveRoot=''; KnownFolderPaths=$null; Apply=$false
|
||
|
|
MaxPathLength=240; MaxNameLength=255; ReportDirectory=''
|
||
|
|
}
|
||
|
|
foreach ($key in $Configuration.Keys) {
|
||
|
|
if (-not $settings.ContainsKey($key)) { throw "Unknown option: $key" }
|
||
|
|
$settings[$key] = $Configuration[$key]
|
||
|
|
}
|
||
|
|
# RMM dropdown strings must never be converted using [bool]'false'.
|
||
|
|
switch -Regex (([string]$settings.Apply).Trim()) {
|
||
|
|
'^(?i:true|\$true|yes|y|1)$' { $apply = $true; break }
|
||
|
|
'^(?i:false|\$false|no|n|0)?$' { $apply = $false; break }
|
||
|
|
default { throw 'Apply must be true/false, yes/no, 1/0, or blank.' }
|
||
|
|
}
|
||
|
|
$maxPath = [int]$settings.MaxPathLength
|
||
|
|
$maxName = [int]$settings.MaxNameLength
|
||
|
|
if ($maxPath -lt 40 -or $maxPath -gt 520) { throw 'MaxPathLength must be between 40 and 520.' }
|
||
|
|
if ($maxName -lt 16 -or $maxName -gt 255) { throw 'MaxNameLength must be between 16 and 255.' }
|
||
|
|
if ($env:OS -ne 'Windows_NT') { throw 'This script requires Windows.' }
|
||
|
|
|
||
|
|
function ConvertTo-PrepPath([string]$Path) {
|
||
|
|
# Absolute drive paths only. UNC roots cannot be used for OneDrive backup.
|
||
|
|
if ($Path -notmatch '^[A-Za-z]:[\\/]' -or $Path -match '[*?"<>|]' -or $Path.Substring(2).Contains(':')) {
|
||
|
|
throw "Use an absolute local drive path: $Path"
|
||
|
|
}
|
||
|
|
$pathText = [IO.Path]::GetFullPath($Path.Replace('/', '\')).TrimEnd('\')
|
||
|
|
if ($pathText.Length -le 2) { throw 'A drive root is not a user folder.' }
|
||
|
|
return $pathText
|
||
|
|
}
|
||
|
|
function Test-PrepWithin([string]$Path, [string]$Root) {
|
||
|
|
return $Path.Equals($Root, [StringComparison]::OrdinalIgnoreCase) -or
|
||
|
|
$Path.StartsWith($Root + '\', [StringComparison]::OrdinalIgnoreCase)
|
||
|
|
}
|
||
|
|
|
||
|
|
# Use Win32 Unicode APIs with extended paths: PowerShell 5.1's provider can
|
||
|
|
# fail while enumerating the very paths this script is intended to repair.
|
||
|
|
if (-not ('Emberkom.OneDrivePathNativeV1' -as [type])) {
|
||
|
|
Add-Type -TypeDefinition @'
|
||
|
|
using System;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using System.ComponentModel;
|
||
|
|
using System.Runtime.InteropServices;
|
||
|
|
namespace Emberkom {
|
||
|
|
public static class OneDrivePathNativeV1 {
|
||
|
|
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
|
||
|
|
public struct Entry {
|
||
|
|
public uint Attributes;
|
||
|
|
public System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Write;
|
||
|
|
public uint SizeHigh, SizeLow, Tag, Reserved;
|
||
|
|
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)] public string Name;
|
||
|
|
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)] public string AlternateName;
|
||
|
|
public bool Directory { get { return (Attributes & 16) != 0; } }
|
||
|
|
public bool UnsupportedReparse { get {
|
||
|
|
return (Attributes & 1024) != 0 && (Tag & 0xFFFF0FFFu) != 0x9000001Au;
|
||
|
|
} }
|
||
|
|
}
|
||
|
|
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
|
||
|
|
static extern IntPtr FindFirstFileW(string path, out Entry data);
|
||
|
|
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
|
||
|
|
static extern bool FindNextFileW(IntPtr handle, out Entry data);
|
||
|
|
[DllImport("kernel32.dll", SetLastError=true)] static extern bool FindClose(IntPtr handle);
|
||
|
|
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
|
||
|
|
static extern bool MoveFileW(string source, string destination);
|
||
|
|
static string Extended(string path) { return @"\\?\" + path; }
|
||
|
|
public static Entry Inspect(string path) {
|
||
|
|
Entry data;
|
||
|
|
IntPtr h = FindFirstFileW(Extended(path), out data);
|
||
|
|
if (h == new IntPtr(-1)) {
|
||
|
|
int error = Marshal.GetLastWin32Error();
|
||
|
|
throw new Win32Exception(error, new Win32Exception(error).Message + ": " + path);
|
||
|
|
}
|
||
|
|
try { return data; } finally { FindClose(h); }
|
||
|
|
}
|
||
|
|
public static Entry[] List(string directory) {
|
||
|
|
Entry data;
|
||
|
|
IntPtr h = FindFirstFileW(Extended(directory) + @"\*", out data);
|
||
|
|
if (h == new IntPtr(-1)) {
|
||
|
|
int error = Marshal.GetLastWin32Error();
|
||
|
|
if (error == 2) return new Entry[0]; // Empty directory.
|
||
|
|
throw new Win32Exception(error, new Win32Exception(error).Message + ": " + directory);
|
||
|
|
}
|
||
|
|
var entries = new List<Entry>();
|
||
|
|
try {
|
||
|
|
do { if (data.Name != "." && data.Name != "..") entries.Add(data); }
|
||
|
|
while (FindNextFileW(h, out data));
|
||
|
|
int error = Marshal.GetLastWin32Error();
|
||
|
|
if (error != 18) throw new Win32Exception(error, new Win32Exception(error).Message + ": " + directory);
|
||
|
|
} finally { FindClose(h); }
|
||
|
|
return entries.ToArray();
|
||
|
|
}
|
||
|
|
public static void Rename(string source, string destination) {
|
||
|
|
// MoveFileW refuses an existing destination; never replace a file.
|
||
|
|
if (!MoveFileW(Extended(source), Extended(destination))) {
|
||
|
|
int error = Marshal.GetLastWin32Error();
|
||
|
|
throw new Win32Exception(error, new Win32Exception(error).Message + ": " + source);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
'@
|
||
|
|
}
|
||
|
|
function Assert-PrepAncestors([string]$Path) {
|
||
|
|
$parts = $Path.Split('\')
|
||
|
|
$prefix = $parts[0]
|
||
|
|
for ($i = 1; $i -lt $parts.Length; $i++) {
|
||
|
|
$prefix += '\' + $parts[$i]
|
||
|
|
$entry = [Emberkom.OneDrivePathNativeV1]::Inspect($prefix)
|
||
|
|
if ($entry.UnsupportedReparse) { throw "Unsupported reparse point (including junction/symlink): $prefix" }
|
||
|
|
if (-not $entry.Directory) { throw "Not a directory: $prefix" }
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
# Resolve the selected user's settings, never SYSTEM's Documents or OneDrive.
|
||
|
|
$folderPaths = $settings.KnownFolderPaths
|
||
|
|
$oneDrive = [string]$settings.OneDriveRoot
|
||
|
|
$profile = [string]$settings.UserProfilePath
|
||
|
|
if ($null -eq $folderPaths -or [string]::IsNullOrWhiteSpace($oneDrive)) {
|
||
|
|
$currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||
|
|
if ([string]::IsNullOrWhiteSpace($profile)) {
|
||
|
|
if ($currentSid -in @('S-1-5-18','S-1-5-19','S-1-5-20')) {
|
||
|
|
throw 'When running as SYSTEM/service account, specify UserProfilePath (or all KnownFolderPaths and OneDriveRoot).'
|
||
|
|
}
|
||
|
|
$profile = $env:USERPROFILE
|
||
|
|
}
|
||
|
|
$profile = ConvertTo-PrepPath $profile
|
||
|
|
$profiles = @(Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' |
|
||
|
|
Where-Object {
|
||
|
|
$p = Get-ItemProperty -LiteralPath $_.PSPath
|
||
|
|
$p.PSObject.Properties['ProfileImagePath'] -and
|
||
|
|
[Environment]::ExpandEnvironmentVariables([string]$p.ProfileImagePath).TrimEnd('\') -ieq $profile
|
||
|
|
})
|
||
|
|
if ($profiles.Count -ne 1) { throw "Cannot uniquely resolve the user profile: $profile" }
|
||
|
|
$userKey = [Microsoft.Win32.Registry]::Users.OpenSubKey($profiles[0].PSChildName)
|
||
|
|
if ($null -eq $userKey) {
|
||
|
|
throw 'The selected user registry hive is not loaded. Sign the user in, or supply all KnownFolderPaths and OneDriveRoot explicitly.'
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
if ([string]::IsNullOrWhiteSpace($oneDrive)) {
|
||
|
|
$accountsKey = $userKey.OpenSubKey('Software\Microsoft\OneDrive\Accounts')
|
||
|
|
$roots = @()
|
||
|
|
if ($accountsKey) {
|
||
|
|
try {
|
||
|
|
foreach ($account in $accountsKey.GetSubKeyNames()) {
|
||
|
|
$accountKey = $accountsKey.OpenSubKey($account)
|
||
|
|
try {
|
||
|
|
$value = [string]$accountKey.GetValue('UserFolder')
|
||
|
|
if ($value) { $roots += $value }
|
||
|
|
} finally { $accountKey.Dispose() }
|
||
|
|
}
|
||
|
|
} finally { $accountsKey.Dispose() }
|
||
|
|
}
|
||
|
|
$roots = @($roots | Sort-Object -Unique)
|
||
|
|
if ($roots.Count -ne 1) { throw 'No unique OneDrive account found. Specify the intended OneDriveRoot.' }
|
||
|
|
$oneDrive = $roots[0]
|
||
|
|
}
|
||
|
|
if ($null -eq $folderPaths) {
|
||
|
|
$shellKey = $userKey.OpenSubKey('Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders')
|
||
|
|
if (-not $shellKey) { throw 'User Shell Folders registry key is missing; supply KnownFolderPaths.' }
|
||
|
|
$folderPaths = @{}
|
||
|
|
try {
|
||
|
|
$userVariables = @{}
|
||
|
|
foreach ($environmentKeyName in @('Environment','Volatile Environment')) {
|
||
|
|
$environmentKey = $userKey.OpenSubKey($environmentKeyName)
|
||
|
|
if ($environmentKey) {
|
||
|
|
try {
|
||
|
|
foreach ($variableName in $environmentKey.GetValueNames()) {
|
||
|
|
$userVariables[$variableName] = [string]$environmentKey.GetValue($variableName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||
|
|
}
|
||
|
|
} finally { $environmentKey.Dispose() }
|
||
|
|
}
|
||
|
|
}
|
||
|
|
$userVariables.USERPROFILE = $profile
|
||
|
|
$userVariables.HOMEDRIVE = $profile.Substring(0,2)
|
||
|
|
$userVariables.HOMEPATH = $profile.Substring(2)
|
||
|
|
foreach ($pair in @(@('Documents','Personal'), @('Pictures','My Pictures'), @('Desktop','Desktop'))) {
|
||
|
|
$value = [string]$shellKey.GetValue($pair[1], '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||
|
|
# Use the selected user's actual environment. The intended
|
||
|
|
# destination could be a DIFFERENT OneDrive account.
|
||
|
|
for ($pass = 0; $pass -lt 10 -and $value -match '%[^%]+%'; $pass++) {
|
||
|
|
$value = [regex]::Replace($value, '%([^%]+)%', [Text.RegularExpressions.MatchEvaluator]{
|
||
|
|
param($match)
|
||
|
|
if ($userVariables.ContainsKey($match.Groups[1].Value)) { return $userVariables[$match.Groups[1].Value] }
|
||
|
|
return $match.Value
|
||
|
|
})
|
||
|
|
}
|
||
|
|
if (-not $value -or $value -match '%[^%]+%') { throw "Cannot resolve $($pair[0]); supply KnownFolderPaths explicitly." }
|
||
|
|
$folderPaths[$pair[0]] = $value
|
||
|
|
}
|
||
|
|
} finally { $shellKey.Dispose() }
|
||
|
|
}
|
||
|
|
} finally { $userKey.Dispose() }
|
||
|
|
}
|
||
|
|
$oneDrive = ConvertTo-PrepPath $oneDrive
|
||
|
|
if ($oneDrive.Length -gt 120) { throw 'OneDriveRoot exceeds the documented 120-character sync-root allowance.' }
|
||
|
|
if ($folderPaths -isnot [hashtable] -or $folderPaths.Count -ne 3) {
|
||
|
|
throw 'KnownFolderPaths must map all three keys: Documents, Pictures, Desktop.'
|
||
|
|
}
|
||
|
|
$mappings = @()
|
||
|
|
foreach ($name in @('Documents','Pictures','Desktop')) {
|
||
|
|
if (-not $folderPaths.ContainsKey($name)) { throw "KnownFolderPaths is missing $name." }
|
||
|
|
$source = ConvertTo-PrepPath $folderPaths[$name]
|
||
|
|
if (Test-PrepWithin $oneDrive $source) { throw "OneDriveRoot cannot be inside a source folder: $source" }
|
||
|
|
foreach ($other in $mappings) {
|
||
|
|
if ((Test-PrepWithin $source $other.Source) -or (Test-PrepWithin $other.Source $source)) {
|
||
|
|
throw 'Known folder source paths must not overlap.'
|
||
|
|
}
|
||
|
|
}
|
||
|
|
$destination = if (Test-PrepWithin $source $oneDrive) { $source } else { $oneDrive + '\' + $name }
|
||
|
|
$mappings += [pscustomobject]@{ Name=$name; Source=$source; Destination=$destination }
|
||
|
|
}
|
||
|
|
$reportParent = [string]$settings.ReportDirectory
|
||
|
|
if (-not $reportParent) { $reportParent = Join-Path ([IO.Path]::GetTempPath()) 'OneDrivePathPreparation' }
|
||
|
|
$reportParent = ConvertTo-PrepPath $reportParent
|
||
|
|
foreach ($mapping in $mappings) {
|
||
|
|
if (Test-PrepWithin $reportParent $mapping.Source) { throw 'ReportDirectory must be outside the folders being scanned.' }
|
||
|
|
}
|
||
|
|
if (Test-PrepWithin $reportParent $oneDrive) { throw 'ReportDirectory must be outside OneDriveRoot.' }
|
||
|
|
$runDirectory = Join-Path $reportParent ((Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0,8))
|
||
|
|
# Reports are intentionally written even in preview / WhatIf mode.
|
||
|
|
$null = [IO.Directory]::CreateDirectory($runDirectory)
|
||
|
|
$planPath = Join-Path $runDirectory 'plan.csv'
|
||
|
|
$resultPath = Join-Path $runDirectory 'results.csv'
|
||
|
|
$journalPath = Join-Path $runDirectory 'journal.csv'
|
||
|
|
$rows = [Collections.Generic.List[object]]::new()
|
||
|
|
$filesScanned = 0
|
||
|
|
$foldersScanned = 0
|
||
|
|
|
||
|
|
function New-PrepRow($Mapping, [string]$Path, [string]$Projected, [string]$Kind, [string]$Status, [string]$Reason) {
|
||
|
|
$relative = if ($Projected) { $Projected.Substring($oneDrive.Length + 1) } else { '' }
|
||
|
|
return [pscustomobject][ordered]@{
|
||
|
|
Folder=$Mapping.Name; Kind=$Kind; Status=$Status; Reason=$Reason
|
||
|
|
OriginalPath=$Path; NewPath=''; ProjectedPath=$Projected; NewProjectedPath=''
|
||
|
|
OriginalPathLength=$Path.Length; ProjectedPathLength=$Projected.Length
|
||
|
|
CloudRelativePathLength=$relative.Length; NewProjectedPathLength=0
|
||
|
|
}
|
||
|
|
}
|
||
|
|
function Test-PrepInvalidName([string]$Name) {
|
||
|
|
return $Name -match '["*:<>?/\\|\x00-\x1F]' -or $Name -match '^ |[ .]$' -or
|
||
|
|
$Name -match '^(?i:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\.|$)' -or
|
||
|
|
$Name -match '(?i)_vti_' -or $Name -match '^(?i:\.lock|desktop\.ini)$' -or $Name.StartsWith('~$')
|
||
|
|
}
|
||
|
|
function Get-PrepShortName([string]$Name, [string]$Identity, [int]$Budget, $Used) {
|
||
|
|
$extension = [IO.Path]::GetExtension($Name)
|
||
|
|
$stem = $Name.Substring(0, $Name.Length - $extension.Length)
|
||
|
|
$sha = [Security.Cryptography.SHA256]::Create()
|
||
|
|
try { $hash = [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Identity))).Replace('-','').Substring(0,8).ToLowerInvariant() }
|
||
|
|
finally { $sha.Dispose() }
|
||
|
|
for ($attempt = 0; $attempt -lt 10000; $attempt++) {
|
||
|
|
$suffix = '~' + $hash
|
||
|
|
if ($attempt) { $suffix += '-' + $attempt }
|
||
|
|
$keep = [Math]::Min($stem.Length, $Budget - $extension.Length - $suffix.Length)
|
||
|
|
if ($keep -lt 1) { return $null }
|
||
|
|
if ([char]::IsHighSurrogate($stem[$keep - 1])) { $keep-- }
|
||
|
|
if ($keep -lt 1) { return $null }
|
||
|
|
$candidate = $stem.Substring(0, $keep).TrimEnd(' ','.') + $suffix + $extension
|
||
|
|
if (-not (Test-PrepInvalidName $candidate) -and $Used.Add($candidate)) { return $candidate }
|
||
|
|
}
|
||
|
|
return $null
|
||
|
|
}
|
||
|
|
|
||
|
|
foreach ($mapping in $mappings) {
|
||
|
|
Write-Host "Scanning $($mapping.Name): $($mapping.Source) -> $($mapping.Destination)"
|
||
|
|
try { Assert-PrepAncestors $mapping.Source }
|
||
|
|
catch {
|
||
|
|
$rows.Add((New-PrepRow $mapping $mapping.Source $mapping.Destination 'Folder' 'ScanError' $_.Exception.Message))
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
$queue = [Collections.Generic.Queue[string]]::new()
|
||
|
|
$queue.Enqueue($mapping.Source)
|
||
|
|
while ($queue.Count) {
|
||
|
|
$directory = $queue.Dequeue()
|
||
|
|
$projectedDirectory = $mapping.Destination + $directory.Substring($mapping.Source.Length)
|
||
|
|
$cloudDirectory = $projectedDirectory.Substring($oneDrive.Length + 1)
|
||
|
|
$foldersScanned++
|
||
|
|
if ($directory.Length -gt $maxPath -or $projectedDirectory.Length -gt $maxPath -or $cloudDirectory.Length -gt 400) {
|
||
|
|
$rows.Add((New-PrepRow $mapping $directory $projectedDirectory 'Folder' 'NeedsFolderCleanup' 'Folder path exceeds the length budget; shorten ancestor folders or reduce nesting.'))
|
||
|
|
}
|
||
|
|
try { $entries = @([Emberkom.OneDrivePathNativeV1]::List($directory) | Sort-Object Name) }
|
||
|
|
catch {
|
||
|
|
$rows.Add((New-PrepRow $mapping $directory $projectedDirectory 'Folder' 'ScanError' $_.Exception.Message))
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
$used = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||
|
|
foreach ($entry in $entries) { $null = $used.Add($entry.Name) }
|
||
|
|
foreach ($entry in $entries) {
|
||
|
|
$path = $directory + '\' + $entry.Name
|
||
|
|
$projected = $projectedDirectory + '\' + $entry.Name
|
||
|
|
$kind = if ($entry.Directory) { 'Folder' } else { 'File' }
|
||
|
|
if ($entry.UnsupportedReparse) {
|
||
|
|
$rows.Add((New-PrepRow $mapping $path $projected $kind 'SkippedReparsePoint' 'Junction, symlink, or unsupported reparse point; subtree not scanned.'))
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if (Test-PrepInvalidName $entry.Name) {
|
||
|
|
$rows.Add((New-PrepRow $mapping $path $projected $kind 'InvalidName' 'Non-length OneDrive name restriction; review manually (desktop.ini and Office lock files normally do not sync).'))
|
||
|
|
}
|
||
|
|
if ($entry.Directory) {
|
||
|
|
if ($entry.Name.Length -gt $maxName) {
|
||
|
|
$rows.Add((New-PrepRow $mapping $path $projected $kind 'NeedsFolderCleanup' 'Folder name exceeds MaxNameLength; review manually.'))
|
||
|
|
}
|
||
|
|
$queue.Enqueue($path)
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
$filesScanned++
|
||
|
|
$budget = [Math]::Min($maxName, [Math]::Min($maxPath - $directory.Length - 1,
|
||
|
|
[Math]::Min($maxPath - $projectedDirectory.Length - 1, 400 - $cloudDirectory.Length - 1)))
|
||
|
|
if ($entry.Name.Length -le $budget -or (Test-PrepInvalidName $entry.Name)) { continue }
|
||
|
|
$row = New-PrepRow $mapping $path $projected 'File' 'Planned' 'Filename exceeds the current/projected path or filename length budget.'
|
||
|
|
$newName = Get-PrepShortName $entry.Name $path $budget $used
|
||
|
|
if (-not $newName) {
|
||
|
|
$row.Status = 'NeedsFolderCleanup'
|
||
|
|
$row.Reason = 'Not enough room for a stem, collision suffix, and unchanged extension. Shorten ancestor folders or reduce nesting.'
|
||
|
|
} else {
|
||
|
|
$row.NewPath = $directory + '\' + $newName
|
||
|
|
$row.NewProjectedPath = $projectedDirectory + '\' + $newName
|
||
|
|
$row.NewProjectedPathLength = $row.NewProjectedPath.Length
|
||
|
|
}
|
||
|
|
$rows.Add($row)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
# Always keep a plan on disk before the first file is renamed.
|
||
|
|
function Export-PrepRows([string]$Path) {
|
||
|
|
if ($rows.Count) { $rows | Export-Csv -LiteralPath $Path -NoTypeInformation -Encoding UTF8 -WhatIf:$false }
|
||
|
|
else {
|
||
|
|
$header = (New-PrepRow $mappings[0] '' '' '' '' '' | ConvertTo-Csv -NoTypeInformation)[0]
|
||
|
|
[IO.File]::WriteAllText($Path, $header + [Environment]::NewLine, [Text.UTF8Encoding]::new($true))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Export-PrepRows $planPath
|
||
|
|
$scanErrors = @($rows | Where-Object Status -eq 'ScanError').Count
|
||
|
|
$journal = $null
|
||
|
|
try {
|
||
|
|
if ($apply -and $scanErrors -eq 0) {
|
||
|
|
$stream = [IO.FileStream]::new($journalPath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
|
||
|
|
$journal = [IO.StreamWriter]::new($stream, [Text.UTF8Encoding]::new($true))
|
||
|
|
$journal.WriteLine('"UtcTime","Status","OriginalPath","NewPath","Message"')
|
||
|
|
$journal.Flush(); $stream.Flush($true)
|
||
|
|
}
|
||
|
|
function Write-PrepJournal($Row, [string]$Status, [string]$Message) {
|
||
|
|
$record = [pscustomobject][ordered]@{ UtcTime=[DateTime]::UtcNow.ToString('o'); Status=$Status; OriginalPath=$Row.OriginalPath; NewPath=$Row.NewPath; Message=$Message }
|
||
|
|
$journal.WriteLine(($record | ConvertTo-Csv -NoTypeInformation)[1])
|
||
|
|
$journal.Flush(); $stream.Flush($true)
|
||
|
|
}
|
||
|
|
foreach ($row in $rows) {
|
||
|
|
if ($row.Status -ne 'Planned') { continue }
|
||
|
|
if (-not $apply) { $row.Status = 'Preview'; continue }
|
||
|
|
if ($scanErrors) { $row.Status = 'NotApplied'; $row.Reason = 'Scan errors prevent all renames in this run.'; continue }
|
||
|
|
if (-not $Caller.ShouldProcess($row.OriginalPath, "Rename to $($row.NewPath)")) { $row.Status = 'NotApplied'; continue }
|
||
|
|
# Write intent durably BEFORE mutating. A journal failure stops the run.
|
||
|
|
Write-PrepJournal $row 'Pending' ''
|
||
|
|
try {
|
||
|
|
$parent = $row.OriginalPath.Substring(0, $row.OriginalPath.LastIndexOf('\'))
|
||
|
|
Assert-PrepAncestors $parent
|
||
|
|
$current = [Emberkom.OneDrivePathNativeV1]::Inspect($row.OriginalPath)
|
||
|
|
if ($current.Directory -or $current.UnsupportedReparse) { throw 'Source became a directory or unsupported reparse point after planning.' }
|
||
|
|
[Emberkom.OneDrivePathNativeV1]::Rename($row.OriginalPath, $row.NewPath)
|
||
|
|
$row.Status = 'Renamed'
|
||
|
|
} catch {
|
||
|
|
$row.Status = 'RenameFailed'; $row.Reason = $_.Exception.Message
|
||
|
|
}
|
||
|
|
Write-PrepJournal $row $row.Status $row.Reason
|
||
|
|
}
|
||
|
|
} finally {
|
||
|
|
if ($journal) { $journal.Dispose() }
|
||
|
|
Export-PrepRows $resultPath
|
||
|
|
}
|
||
|
|
$renamed = @($rows | Where-Object Status -eq 'Renamed').Count
|
||
|
|
$previewed = @($rows | Where-Object Status -eq 'Preview').Count
|
||
|
|
$unresolved = @($rows | Where-Object { $_.Status -notin @('Renamed','Preview') }).Count
|
||
|
|
Write-Host "Scanned $filesScanned files / $foldersScanned folders. Preview: $previewed. Renamed: $renamed. Review needed: $unresolved."
|
||
|
|
Write-Host "Results: $resultPath"
|
||
|
|
if ($scanErrors) { Write-Warning 'Scan incomplete. No files were renamed. Resolve ScanError rows and rerun.' }
|
||
|
|
if ($unresolved) { Write-Warning 'Review unresolved/skipped rows; this run does not establish OneDrive backup readiness.' }
|
||
|
|
[pscustomobject]@{
|
||
|
|
Mode=$(if ($apply) { 'Apply' } else { 'Preview' }); FilesScanned=$filesScanned; FoldersScanned=$foldersScanned
|
||
|
|
Previewed=$previewed; Renamed=$renamed; ReviewNeeded=$unresolved; ScanErrors=$scanErrors
|
||
|
|
ReportDirectory=$runDirectory; PlanPath=$planPath; ResultPath=$resultPath
|
||
|
|
JournalPath=$(if ($journal) { $journalPath } else { $null })
|
||
|
|
}
|
||
|
|
} $Options $PSCmdlet
|