Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I detect if a file has been locked by another process in powershell?

I have read some examples of checks that catches the exception that occurs when trying to read the file. This some how does not feel good to me.

share|improve this question
up vote 1 down vote accepted

In general, you can't be sure that you have the access to a file that you want without actually trying to use it. Even if you could do a proper check, between the time you do the check and the time you use the file, the state could change.

For example, the user supplies you with a file name to read. You check if the file exists, see that it does, and decide to proceed. Before you try to read it, another program deletes it. Or maybe the file is on a network share and the network goes down.

So, try to use the file, catch the exception, and fail gracefully.

Also, remember to only catch and dismiss exceptions that you understand and expect.

share|improve this answer
Thank you Jay, you are of course right, I did not think of that. – elgrego Mar 11 '11 at 19:15

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.