This PowerShell script schedules a file for deletion on the next system reboot by modifying the Windows Registry key PendingFileRenameOperations.
Windows allows certain files to be deleted on reboot if they are locked or in use. This script adds the target file to the appropriate registry value so that it is deleted before the next Windows startup.
DeleteFileonNextReboot.ps1: The main PowerShell script.
The script:
- Verifies the file exists.
- Converts the file path to a format compatible with the Windows Session Manager.
- Appends the file path (in delete mode) to the
PendingFileRenameOperationsregistry key. - Upon reboot, Windows deletes the file.
- Open PowerShell as Administrator.
- Modify the script to set the correct file path:
$fileToDelete = "C:\Path\To\File.txt"
- Run
DeleteFileonNextReboot.ps1as admin - Reboot System
Windows OS
Administrator privileges (required to modify the registry)
PowerShell 5.1 or later
The script modifies the following registry value:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations
Each entry is a pair of strings:
Source path with \??\ prefix
Null destination string ("") indicates deletion
Use caution when modifying the registry.
Ensure the file path is correct to avoid unintended deletions.
Back up your registry before running the script in production environments.
This script is provided as-is without warranty. Use at your own risk.
Scheduled deletion of: C:\Path\To\File.txt on next reboot.