0

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Rakha
  • 1,874
  • 3
  • 26
  • 60

2 Answers2

5

Try this:

Start-Process Notepad.exe U:\test.txt -Wait
Remove-Item U:\test.txt
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
guiwhatsthat
  • 2,349
  • 1
  • 12
  • 24
  • Ah yes, wait! I should've expected that :) Thank you so much it works exactly as needed. – Rakha Apr 12 '17 at 14:12
1

So, I'm limited to replying in an 'answer' because of my reputation.

Basically, my comment would have been "Does this need to be opened in a text file?"

My alternate suggestions would be to do maybe one of the following instead

$content | Out-GridView

Or maybe

$content | Format-Table

You should still see all the data, and still be able to copy data from it without saving a file anywhere that then needs deleting.

Would this be acceptable?

Ross Lyons
  • 161
  • 4
  • 14
  • Good solution however the txt file provides the perfect formatting so it's needed in this case. Thank you! – Rakha Apr 12 '17 at 14:12