Get the file owner from bulk list of .CSV file

This topic contains 5 replies, has 2 voices, and was last updated by  Server Administrator 4 years, 5 months ago.

  • Author
    Posts
  • #7614

    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

  • #7618

    Dave Wyatt
    Moderator

    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
    
  • #7624

    Mr. Wyatt,

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

  • #7630

    Dave Wyatt
    Moderator

    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.

  • #7631

    Dave Wyatt
    Moderator

    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
    
  • #7632

    Thanks Dave, it works perfectly 🙂

You must be logged in to reply to this topic.