CSG
CSG

Reputation: 277

batch: get the name of the owner of a folder

the only command that i know to get the owner of a folder in a batch script is:

dir %foldername% /q 

this has two problems:

  1. it shows in a list all foldername's content, so i've to read only the first row (which contains < DIR > and ".") or you've to run

    dir %parent_of_foldername% /q | findstr "%foldername%"

  2. if the owner have a long name (exemple:TrustedInstaller) this will be trimmed

here is my c:\

13/03/2013  18.33    <DIR>          NT SERVICE\TrustedInstaProgram Files

13/03/2013  18.33    <DIR>          NT SERVICE\TrustedInstaProgram Files (x86)

Then how can i get the owner's name of a folder in a batch script?

Upvotes: 1

Views: 6448

Answers (3)

Nate Hekman
Nate Hekman

Reputation: 6657

Jesper Johansson, the author of http://msinfluentials.com/blogs/jesper/archive/2007/07/02/show-the-owner-of-a-file.aspx, laments that there is no built-in command besides dir /q but lists a few other command-line tools that could work.

  • SubInACL.exe
  • FileACL.exe (I couldn't find this one available anymore)

Upvotes: 0

Magoo
Magoo

Reputation: 79982

@ECHO OFF
SETLOCAL
SET "owner="
FOR /f "tokens=2delims=\" %%i IN ('dir /q "%~1"' ) DO IF NOT DEFINED owner CALL :setown %%i
ECHO owner of "%~1" is %owner%

GOTO :eof

:setown
SET owner=%*
:setownl
SET $2=%2
IF defined $2 shift&GOTO setownl
IF NOT "%1"=="." SET "owner="&GOTO :eof
SET owner=%owner:~0,-2%
GOTO :eof

is my solution. Works for me...

Upvotes: 0

Endoro
Endoro

Reputation: 37569

You can try this:

@echo off &setlocal
set "foldername=c:\temp"
set "owner="

for /f "tokens=3*" %%i in ('dir /q %foldername%^|findstr "<DIR>"') do if not defined owner set "owner=%%j"
echo %owner%

.. and the owner without the computer name:

@echo off &setlocal
set "foldername=c:\temp"
set "owner="

for /f "tokens=1*delims=\" %%i in ('dir /q %foldername%^|findstr "<DIR>"') do if not defined owner set "owner=%%j"
echo %owner%

And third method (returns the full name on my machine):

@echo off &setlocal
set "foldername=c:\temp"
set "owner="

for /f "tokens=2delims=\:" %%i in ('cacls "%foldername%" ^| find "%computername%"') do set "owner=%%i"
echo %owner%

Upvotes: 2

Related Questions