Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Import-CSV and Takeown.

$
0
0

I'm currently trying to come up with a way to search an entire folder directory to find all objects that a particular user is owner to, export that list to csv, then import that csv and using takeown to grant local Administrators Owner.

Scouring the internet, I've been able to come up with this Powershell script to scan a directory and export the findings to a csv.

param(
[string]$username = "NameofUserSearchingFor",
[string]$logfile
)
Set-ExecutionPolicy Unrestricted

if ($logfile -eq "") {
    $logfile = "c:\" + $username + "-Owner.csv"
    Write-Host "Setting log file to $logfile"
}

#Path to search in
[String]$path = "c:\TestFolder"
[String]$AD_username = "Domain\" + $username

#check that we have a valid AD user
if (!(Get-ADUser $AD_username)){
    Write-Host "ERROR: Not a valid AD User: $AD_username"
    Exit 0
}

Write-Output "$username" | Out-File -FilePath $logfile

$files = Get-ChildItem $path -Recurse

ForEach ($file in $files)
{
    $f = Get-Acl $file.FullName

    if ($f.Owner -eq $AD_username)
    {
        Write-Output $file.FullName | Out-File -FilePath $logfile -Append
    }
}
exit 0

That script exports data in the form of:

NameofUserSearchingFor
C:\TestFolder\TestFolder1
C:\TestFolder\TestFolder2
C:\TestFolder\TestFolder1\test1.txt
C:\TestFolder\TestFolder2\test2.txt

I'd like to use takeown to read each line of text and take ownership for local Administrators.  

The script i'm trying to use doesn't do anything though.

#Local Admininstrator Take Ownership
$rows = Import-Csv "c:\NameofUserSearchingFor-Owner.csv"
    ForEach ($row in $rows) 
    {
    takeown /A /F $row
    }

Perhaps I'm going about this all wrong.  I'm relatively new to Powershell and have been trying to come up with a way to do this for the past 3 days.

Any assistance would be greatly appreciated!

*Update*

If I reconfigure the takeown portion a bit to this:

#Local Admininstrator Take Ownership
$Path = "c:\NameofUserSearchingFor-Owner.csv"
$rows = Import-Csv $Path
    ForEach ($line in $rows) 
    {
    takeown /A /F $Path
    }

The result is:

SUCCESS: The file (or folder): "c:\NameofUserSearchingFor-Owner.csv" now owned by the administrators group.

But will repeat as many times as there are lines of text in the csv.  So if there are 4 lines of text in the csv, that line will repeat 4 times.  I find it interesting that it knows how many lines there are but instead of granting local Administrator the owner to the path specified in the line it will instead grant local Administrator to the csv file.


Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>