howdoicode
howdoicode

Reputation: 961

Self-deleting PowerShell script deletes all contents but not the containing/parent folder

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.

Upvotes: 1

Views: 1604

Answers (2)

howdoicode
howdoicode

Reputation: 961

I figured out the solution. I experimented with using Start-Process instead, which creates a separate process altogether. I also discovered not to use -NoNewWindow switch with it, otherwise I got the same results as with Invoke-Expression.

The following code works, deleting the entire folder contents and the folder itself:

Start-Process -FilePath "cmd.exe" -ArgumentList "/c `"cd c:\ & rmdir C:\test /s /q`""

Upvotes: 2

Guenther Schmitz
Guenther Schmitz

Reputation: 1999

I assume that the file script.ps1 is located in the path c:\test which 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.

Start-Job -Name RemoveFolder -ScriptBlock {Start-Sleep 2;Remove-Item -LiteralPath 'C:\test' -Force -Recurse}

Upvotes: 1

Related Questions