Skip to content

Instantly share code, notes, and snippets.

Created November 20, 2013 15:47
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
PowerShell command to delete a file, if possible immediately, and if it is in use at the next boot.
[string] $path
# the code below has been used from
# with inspiration from
# and error handling from
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public class Posh
public enum MoveFileFlags
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);
public static bool MarkFileDelete (string sourcefile)
return MoveFileEx(sourcefile, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
$path = (Resolve-Path $path -ErrorAction Stop).Path
try {
Remove-Item $path -ErrorAction Stop
} catch {
$deleteResult = [Posh]::MarkFileDelete($path)
if ($deleteResult -eq $false) {
throw (New-Object ComponentModel.Win32Exception) # calls GetLastError
} else {
# write-host "(Delete of $path failed: $($_.Exception.Message) Deleting at next boot.)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment