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.
The second foreach has no input object to iterate over. So either
When you use
ForEach-Object
, you need to return the current object for it to go through the pipe and into the next foreach. You can usereturn
for this, or just type the current object variable ($_
) at the end.Since you are passing
$owner
, you don't need to enclose it with quotations. Just use the variable.Don't use single quotations for variables because single quotations output the string with literal text you typed. So it's literally
$owner
and not value of$owner
variable.Code:
Also, you don't need 2 foreach loops. Why not just join them? You can use
Write-Host
to output the string you wanted.