Powershell read from CSV set variables

csvpowershell

I have a csv file with two columns "Path" and "Owner".

I've created the below script and it can read from the CSV file, but when I attempt to assign the variables from the csv it fails.

Import-Csv C:\test\output.csv | ForEach-Object {
    $Path = $_.path
    $owner = $_.owner
    "The username is $Path and the owner is $owner"
}
ForEach-Object {
    $Path = $_.path
    $owner = $_.owner

    $Account = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList '$owner'
    $Acl = Get-Acl -Path $Path
    $Acl.SetOwner($Account)

    Set-Acl -Path $owner -AclObject $Acl
}

The output is correct from the first segment and shows the path and the owner, but the second part doesn't set the owner according to the path.

Best Answer

The second foreach has no input object to iterate over. So either

  • import to a variable and pipe it twice to the foreach loops
  • import twice

$csv = import-csv c:\test\output.csv 
$csv | foreach-object {
  $Path = $_.path
  $owner =$_.owner
  "The username is $Path and the owner is $owner"
}
$csv | ForEach-Object {
    $Path = $_.path
    $owner =$_.owner
    $Account = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList "$owner"
    $Acl = Get-Acl -Path $path
    $Acl.SetOwner($Account);
    Set-Acl -Path $Path -AclObject $Acl
}