I'm trying to have the PowerShell 5.1 script self-delete itself, along with the entire folder contents (including subfolders). I'm using the below code, which works to a point. It does delete all of the folder's contents (including the PowerShell script), but it does NOT delete the folder itself.
script.ps1:
# Main code
# At end of script
Invoke-Expression -Command "cmd.exe /c rmdir `"C:\test`" /s /q"
After running the above code, C:\test still exists, but empty. How can I have the script also remove folder too?
Aditional Note
I've also tried using Remove-Item -Path "C:\test" -Force -Recurse at the end of the script, but it produces the following error:
Remove-Item : Cannot remove the item at 'C:\test' because it is in use.
I discovered that it's a known issue when Remove-Item is used to delete the script itself.
I assume that the file
script.ps1is located in the pathc:\testwhich should be deleted - so as long as the script is running the folder is in use. I would therefore create a PowerShell job at the very end of the script which waits some seconds and thereafter delete that folder.