How to close file for deletion

I am trying to figure out a way to close an open file via PS. I have a script that uses Start-Process to open a Java JAR file that encrypts data. The JAR completes the file encryption, then the process ends. However, the file it encrypted is open and I cant remove it using Remove-Item which is also part of the script.

Once the Script finishes, the file is unlocked and I can delete it. However, I need the PS script to delete the file. Using OpenFiles.EXE, I can see the file is open by Powershell.EXE and thusly I feel as though I should be able to unlock and delete the file, yet I am failing to find a way.

The likely first suggestion will be to use PS to encrypt the file, sadly, I MUST use the JAR file. I have a small function that detects if the file is locked using System.IO and it indeed reports the file is locked, I just have not found a way to unlock it using PS so I can delete it.

Thanks in advance for any help.

Without seeing your code it would be wild guessing. So please share your code (formatted as code using the code posting tag (“PRE”)). Thanks

My first wild guess would be to use a job to encrypt the file using java.

Sorry, script is too big with too many moving parts to post.

I will try the job approach and see where that gets me. Thanks.

It sounds like the script deserves a makeover anyway. You might break your large script into smaller parts. Those usually are easier to maintain and easier to debug if needed. :wink:

I totally agree. I am actually in the process of researching just that :). Any pointers/links would be greatly appreciated.

Use Get-Process cmdlet to find what process encrypted and opened the file then use Stop-Process cmdlet to stop the process.

# Get and stop java process
Get-Process -Name javaw | Stop-Process
# Get and stop notepad process
Get-Process -Name notepad | Stop-Process

Actually, there is no java process still running, it closes as expected. Running “openfiles” shows the encrypted file open via PowerShell.exe, not javaw, hence the reason I feel I should be able to delete the file from the script.

Deleting the file is for clean up purposes and not the end of the world if I cant get rid of it.

Thanks for the help.

You could try to start a second Powershell instance. Either with a job or simply using Start-Process.