Author Posts

June 19, 2013 at 4:25 pm

Hi,

 

I wonder if this is possible with Powershell script, I need to get the owner of files which I have the list in .CSV file as the absolute folder path so that I can get the result in secondary column which list the owner of the files.

 

The first column of the CSV:

F:\Directory1\file1.zip

H:\Directory3\file4.docx

.

.

.

F:\Directory99\file234324.bat

 

The second column is none, but I'd like it to be:

Logonname1

Logonname2

.

.

.

Logonname99

June 19, 2013 at 4:56 pm

Sure.  Call Get-Acl on the path, and then call the GetOwner() method on the resulting object (passing in the [System.Security.Principal.NTAccount] type as an argument to GetOwner).

Example:

$csvPath = "c:\scripts\file.csv"
Import-Csv -Path $csvPath -Header "FileName","Owner" | ForEach-Object { $_.Owner = (Get-Acl -Path $_.FileName).GetOwner([System.Security.Principal.NTAccount]); $_ } | ConvertTo-Csv -NoTypeInformation

June 19, 2013 at 5:07 pm

Mr. Wyatt,

Thanks for the quick reply, so how can I save the result into the CSV file ?

June 19, 2013 at 5:11 pm

Just use Export-Csv instead of ConvertTo-Csv. I did ConvertTo-Csv in my example because that would dump output to the screen instead of overwriting your file, but it was mainly to show the use of Get-Acl and GetOwner().

In a production script, I wouldn't do it all on one pipeline like that, and there would be code to check for errors.

June 19, 2013 at 5:15 pm

Also, I overlooked this when I was looking at the members of the object returned by Get-Acl, but you can just use the "Owner" property rather than typing out that whole .NET method:

$csvPath = "c:\scripts\file.csv"
Import-Csv -Path $csvPath -Header "FileName","Owner" | ForEach-Object { $_.Owner = (Get-Acl -Path $_.FileName).Owner; $_ } | ConvertTo-Csv -NoTypeInformation

June 19, 2013 at 5:20 pm

Thanks Dave, it works perfectly 🙂