0

I have a script that needs to do some cleanup whenever a shutdown or restart is happening. It essentially only removes 2 files and renaming 2 other files when the shutdown happens.

I tried using these:

$sysevent = [microsoft.win32.systemevents]
Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnding" -Action { #Do cleanup }
Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnded" -Action { #Do cleanup }

But it doesn't seem to be working

How can make it, so that it kicks in the cleanup whenever a shutdown or restart happens?

wads
  • 123
  • 11
  • When starting up you need to run a utility that checks if two files exist and remove. – jdweng Nov 18 '22 at 09:55
  • The cleanup itself works - it just doesn't fire when the machine is shutting down or restarting – wads Nov 18 '22 at 09:57
  • You cannot guarantee on shutdown the files will be deleted. It has to be done on startup or when application is started. So you cannot use an event do remove files. I recommend adding at start of app/service that you check for the two files and remove. Only issue is if more than one version of the app/service is used. – jdweng Nov 18 '22 at 10:01
  • 1
    Windows has an API, `MoveFileEx` that can be used to schedule files to be renamed or deleted on reboot. https://stackoverflow.com/a/73804178/7571258 -- If you supply a path for the 2nd parameter, the file will be moved/renamed, if you pass `[NullString]::Value` as in the example, the file will be deleted. – zett42 Nov 18 '22 at 10:56
  • That would solve my issue! Thank you :) – wads Nov 18 '22 at 13:09
  • Thanks for confirming! So we can now close as duplicate: [Delete a locked file using powershell](https://stackoverflow.com/questions/69518375/delete-a-locked-file-using-powershell) – zett42 Nov 18 '22 at 17:52

0 Answers0