I was hoping to find some help regarding a line of script I’ve written.
For my home situation, I’ve brewed together something that at one point, tries to delete some obsolete files (in this case .jpg files in my Music folder):
For this, I also wanted the line to log exactly which files have been deleted with the part:
Add-Content $LogFile
This works just the fine. The variable LogFile contains all information I need, except for one thing…
Whenever a file can’t be deleted (because for example lack of permissions), the log will still show “Deleting file: something.jpg”.
Is it possible to also include the failed attempts at deleting a file, while still keeping the line as simple as possible?
You’d need to use some sort of error detection code. In this case, a try/catch would be most appropriate. If you want to keep it all crammed onto one line, it might look something like this:
There’s a good “gotcha” to be aware of in that code, Sam. When you enter a catch block, the $_ variable is overwritten to contain the terminating error that was caught. That’s why I saved the value of $_ as of the beginning of the ForEach-Object block into another variable called $file first, in my example.
Indeed the try/catch method is working perfectly. In the end, I’ve sacrificed my one-line wishes for a good working script.
Sam&Dave, thank you for your help with this.