1

In .bat files for Windows's cmd.exe, recursively taking ownership of a folder's content goes

takeown /f foldername /r /d Y >nul: 2>&1

Problem is, it works only if in the current locale the word for Yes starts with the letter Y. E.g. it fails in French, which uses Oui, thus requires O.

Any workaround?

fgrieu
  • 365
  • 4
  • 17

1 Answers1

3

You can use the COPY command to determine the "yes" response used by the machine.

@echo off
setlocal
for /f "delims=(/ tokens=2" %%Y in (
  '"copy /-y nul "%~f0" <nul"'
) do if not defined yes set "yes=%%Y"
takeown /f foldername /r /d %yes% >nul 2>&1

The %yes% value will be the entire word, not just the first letter. I think that will work just fine. But if I am wrong, you can simply use %yes:~0,1% instead.

Update As fgrieu points out in his comment, the above will fail if the script path includes (. Failure due to other special characters could be fixed by ditching the outer double quotes and escaping the redirection. But the ( is problematic.

Here is an alternate strategy that works as long as %temp% points to a valid folder that the user has write privileges. It creates a file with a name known not to cause problems. If the file already exists in %temp% then it is undisturbed.

@echo off
setlocal
pushd "%temp%"
if not exist getYes.tmp (call ) >>getYes.tmp
set "yes="
for /f "delims=(/ tokens=2" %%Y in (
  '"copy /-y nul getYes.dummy <nul"'
) do if not defined yes set "yes=%%Y"
takeown /f foldername /r /d %yes% >nul 2>&1

I suppose there is no guarantee that COPY and TAKEOWN use the same yes response, but I would be shocked if they don't.

dbenham
  • 651
  • 4
  • 12
  • 1
    Clever hack; but I fear it will fail if the bat file's name or one of it's parent's directory includes special characters, including but not limited to `(`. Also this assumes localization of takeown.exe is the same as that from cmd.exe. In this line of thought, we could parse takeown's help obtained line by line with `@for /f "delims= " %%L in ('takeown /?') do @ `and pray that the first occurrence of a `"?"` following `/D` is the local for `"Y"`. Oh my.. – fgrieu Feb 26 '20 at 17:15
  • @fgrieu - Good catch with ( in the path. See my update for a solution to that issue. I would be willing to take my chances that TAKEOWN and COPY use the same affirmative response. I think it is highly unlikely that a universal parsing expression could be formulated to extract the affirmative response from the TAKEOWN help. – dbenham Feb 26 '20 at 19:28