Skip to content

Commit 63496bd

Browse files
authored
Create Delete_files_using_MoveFileExA.ps1
1 parent 2c8bcb5 commit 63496bd

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Delete_files_using_MoveFileExA.ps1

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Delete files using MoveFileExA
2+
# https://devblogs.microsoft.com/scripting/weekend-scripter-use-powershell-and-pinvoke-to-remove-stubborn-files/
3+
$Signature = @{
4+
Namespace = "WinAPI"
5+
Name = "DeleteFiles"
6+
Language = "CSharp"
7+
#CompilerParameters = $CompilerParameters
8+
MemberDefinition = @"
9+
public enum MoveFileFlags
10+
{
11+
MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004
12+
}
13+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
14+
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);
15+
public static bool MarkFileDelete (string sourcefile)
16+
{
17+
return MoveFileEx(sourcefile, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
18+
}
19+
"@
20+
}
21+
22+
if (-not ("WinAPI.DeleteFiles" -as [type]))
23+
{
24+
Add-Type @Signature
25+
}
26+
27+
try
28+
{
29+
Get-ChildItem -Path D:\Folder -Recurse -Force -ErrorAction Ignore | Remove-Item -Recurse -Force -ErrorAction Stop
30+
}
31+
catch
32+
{
33+
# If files are in use remove them at the next boot
34+
Get-ChildItem -Path D:\Folder -Recurse -Force -ErrorAction Ignore | ForEach-Object -Process {[WinAPI.DeleteFiles]::MarkFileDelete($_.FullName)}
35+
}

0 commit comments

Comments
 (0)