Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PowerShell script for moving / renaming files with otherwise invalid filenames
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
You can’t perform that action at this time.