I have been trying to have powershell or batch scripts delete a folder that contains all my scripts when I am finished.
Originally I tried Remove-Item -Path "C:\Tool" -Recurse -Force which worked no problem if run as a script for a location outside of C:\Tool. It would complain the files were in use when run from a script within.
After some research I found &cmd.exe /c rd /s /q "C:\Tool" which worked much better, but even though I closed the GUI, the command wouldn't delete the img files/folders in use.
Both the above commands run perfectly when initiated from a USB drive.
Previously I created a second script in the temp folder which would delete all the files and then itself. I am looking for a new way to do this to streamline the new design I'm working on. I want the script to work from either within C:\Tool or from a USB drive.
The control flow is such:
1)Script loads all functions
2)GUI is displayed (which contains imgs)
3)Button is pressed
4)GUI is closed
5)Folder containing script is deleted
Step 5 is my issue as already explained. Not all files are removed by either attempted commands and variations of commands.
I want step 5 to work regardless is command is called from a button on the GUI, it autoruns as a part of the script, or a script in another location such as a USB calls it to delete the folder C:\Tool
We don't know the specifics of how your GUI is displayed, but, assuming you're using a WinForms GUI constructed in PowerShell code, your problem may be how your GUI construction code loads images from files in the folder that you later want to delete.
Notably, if you use something like:
the specified file apparently stays open for the remainder of the PowerShell session, and you won't be able to delete your folder.
The solution is to create a new image instance in memory that copies the loaded-from-file image, and to then dispose of the loaded-from-file image, which releases the lock on the underlying file, as demonstrated in this [C#] answer.
Here's a minimal script,
demo.ps1, that demonstrates the approach:Save it to its own, temporary, throw-away folder.
Copy a small image file named
demo.pnginto the same folder.Then invoke it as
<temp-folder>/demo -SelfDestructto see it in action; the need to specify-SelfDescriptis a precaution, given that accidental invocation would wipe out the entire folder in which the script lives.demo.ps1:Here's a variant that triggers the removal by button click, via an event handler: