Skip to content

Instantly share code, notes, and snippets.

@poizan42 poizan42/DeleteAnyFile.ps1
Last active Nov 24, 2017

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