Overwrite a read-only file in batch with xcopy
Asked Answered
G

2

5

We have an internal excel addon we deploy on a regular basis across a number of UNC directories. Each copy is set to read only so that the users can't alter it on accident. The "deployment" process involves going to each directory, and copying the file into the location with a click and drag. Since the file is read only there is no conflict, users shutdown the excel window and restart, they have the updates.

I've set out to replace this with a batch file that does it automatically as the number of directories continues to grow and there is occasionally an error such as forgetting to set the file to read only.

I'm using xcopy like so:

xcopy "%workingdir%%filename%" "%uncpath%%targetdirectory%" /y /k

And I'm getting access denied on writing over the file. Is there a way to achieve this functionality that we get from click and drag using Batch? I'm certain that there must be a way to do it but all the solutions we've seen so far involve code to momentarily remove "Read Only" and then copy the file. I don't believe that is a viable solution as it may lock access to the file if someone is loading it at that split second.

EDIT: Discovered moments after posting this that it is the xcopy flag /r Not sure how I missed it, just one of those days I suppose. Thanks.

Gird answered 12/1, 2016 at 20:7 Comment(0)
S
3

If this is a read-only file that will not have the write flag enabled hence you cannot edit it. My idea / workaround for you is to make a file editable and then modify then convert back to read-only.

attrib -r file.txt

your code goes here

attrib +r file.txt

See if this works for you, let me know if you have any questions.

Secundas answered 13/1, 2016 at 2:30 Comment(1)
Hey thanks, I left the question up even though I'd found the answer. This will also work, but it was something I wanted to avoid doing since it could cause conflict. Edit, see my edit from before.Gird
R
7

Adding OP's edit as an actual answer:

xcopy source [destination] /y /r

/y    Suppress prompt to confirm overwriting a file.
/r    Overwrite read-only files.

Sources: ss64.com, Microsoft Docs

Redmer answered 26/9, 2018 at 8:16 Comment(0)
S
3

If this is a read-only file that will not have the write flag enabled hence you cannot edit it. My idea / workaround for you is to make a file editable and then modify then convert back to read-only.

attrib -r file.txt

your code goes here

attrib +r file.txt

See if this works for you, let me know if you have any questions.

Secundas answered 13/1, 2016 at 2:30 Comment(1)
Hey thanks, I left the question up even though I'd found the answer. This will also work, but it was something I wanted to avoid doing since it could cause conflict. Edit, see my edit from before.Gird

© 2022 - 2024 — McMap. All rights reserved.