Getting Owner of a File in Windows

Through Windows’ WMI Service you can find out who the owner is of a file. This is somewhat similar to the user/group owner of a file in UNIX or Linux, as shown in the example below, where the file myfile.txt is owned by user root and group root.

$ ls -al myfile.txt 
-rw-rw-r-- 1 root root 0 Jul  6 14:57 myfile.txt

With the following AutoIt code, you can get the owner username of a given file. It should be relatively easy to convert this code to a Visual Basic or C# equivalent, if needed.

Func GetOwner($file)
    Local $computer = "."
    Local $wmi = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $computer & "\root\cimv2")

    Dim $res
    $res = $wmi.ExecQuery("ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='" & $file & "'} WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner")

    For $val In $res
        Return $val.AccountName
    Next
EndFunc

Leave a Reply

Your email address will not be published. Required fields are marked *

*