Last active
November 24, 2017 13:33
-
-
Save poizan42/9ef1cdfb16e2515b586719900072599d to your computer and use it in GitHub Desktop.
PowerShell script for deleting files with otherwise invalid filenames
This file contains hidden or 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]$filename) | |
$signature = @' | |
[DllImport("kernel32.dll", ExactSpelling=true, CharSet=CharSet.Unicode, SetLastError=true)] | |
public static extern uint DeleteFileW( | |
string lpFileName); | |
'@ | |
$type = $null | |
try | |
{ | |
$type = [DeleteAnyFile.Win32Utils] | |
} | |
catch | |
{ | |
} | |
if ($type -eq $null) | |
{ | |
$type = Add-Type -MemberDefinition $signature ` | |
-Name Win32Utils -Namespace DeleteAnyFile ` | |
-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::DeleteFileW((MakeLongPath $filename)) -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