Created
November 24, 2017 13:37
-
-
Save poizan42/ed45fae25e6c482a3d9fe2bdac84894b to your computer and use it in GitHub Desktop.
PowerShell script for moving / renaming files with otherwise invalid filenames
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param([String]$existingFilename, [String]$newFilename) | |
$signature = @' | |
[DllImport("kernel32.dll", ExactSpelling=true, CharSet=CharSet.Unicode, SetLastError=true)] | |
public static extern uint MoveFileW( | |
string lpExistingFileName, string lpNewFileName); | |
'@ | |
$type = $null | |
try | |
{ | |
$type = [MoveAnyFile.Win32Utils] | |
} | |
catch | |
{ | |
} | |
if ($type -eq $null) | |
{ | |
$type = Add-Type -MemberDefinition $signature ` | |
-Name Win32Utils -Namespace MoveAnyFile ` | |
-Using System.Text -PassThru | |
} | |
function MakeLongPath([string]$path) | |
{ | |
if ($path.StartsWith("\") -eq !$path.StartsWith("\\") ) | |
{ | |
$pwdRoot = [System.IO.Path]::GetPathRoot((pwd).ProviderPath) | |
$path = [System.IO.Path]::Combine($pwdRoot, $path.Substring(1)) | |
} | |
elseif (![System.IO.Path]::IsPathRooted($path)) | |
{ | |
$path = [System.IO.Path]::Combine((pwd).ProviderPath, $path) | |
} | |
if ($path.StartsWith("\\?\")) | |
{ | |
$f = $path | |
} | |
elseif ($path.StartsWith("\\")) | |
{ | |
$f = "\\?\UNC\"+$path.Substring(2) | |
} | |
elseif ($path.Length -ge 2 -and $path[1] -eq ":") | |
{ | |
$f = "\\?\$path" | |
} | |
$parts = $f.Split("\") | |
$pathStack = [System.Collections.Generic.Stack[String]]::new() | |
foreach ($part in $parts) | |
{ | |
if ($part -eq ".") | |
{ | |
continue | |
} | |
elseif ($part -eq "..") | |
{ | |
$pathStack.Pop() > $null | |
} | |
else | |
{ | |
$pathStack.Push($part) | |
} | |
} | |
return [String]::Join('\', [System.Linq.Enumerable]::Reverse($pathStack)) | |
} | |
if ($type::MoveFileW((MakeLongPath $existingFilename), (MakeLongPath $newFilename)) -eq 0) | |
{ | |
throw [System.ComponentModel.Win32Exception]([System.Runtime.InteropServices.Marshal]::GetLastWin32Error()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment