Search code examples
filepowershelldelete-filenotepad

Delete a .txt file after it's closed?


I want to delete a file after it's been closed.

Example:

$content | Out-File info.txt
Invoke-Item info.txt

This opens the file info.txt with the content of $content.

Now all I want to do is, when this file is closed, delete it.

Any idea how to do this? I supose I need to do something like check if info.txt is open, if not then run Remove-Item info.txt?

Right now I use this "dirty" solution which is force deleting the file after 3 seconds, giving it time to open in Notepad:

Start-Sleep -s 3
Remove-Item -Force -ErrorAction SilentlyContinue info.txt

It remains open in notepad for viewing even though it doesn't exist anymore and when I close the file it's already deleted so it kinda works but I'm still looking for a proper way to check if file is closed before deleting.


Solution

  • Try this:

    Start-Process Notepad.exe U:\test.txt -Wait
    Remove-Item U:\test.txt