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.

1 Answer 1


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.

  • Thank you Jay, you are of course right, I did not think of that.
    – elgrego
    Commented Mar 11, 2011 at 19:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .