Hello all, I know there is a lot to take in here, but im not sure where the failure is because the results are not fully wrong. This script is used to generate emails, it is looping the correct amount of times (per lines in CSV file) however it is pulling the final line from the CSV file to populate the data.
Its obvious there is something wrong with my foreach statement at the final line, however im unsure of what that is wrong, so I just put it all out there.
I wont lie, i’m still learning… here is what I understand, and maybe someone can fill in the blanks. I have always used “foreach ($line in $input_csvfile)” for my loop, I was under the understanding that $line is something that powershell already understands (I only say this because other scripts such as the one below work correctly). So the looping statement doesn’t actually use $line except when I am calling it to run thru all lines within the CSV. This is looping the correct amount of times…
lets say csv file has this data:
line 1 is($Fulfiller = Tom, $Owner = my-group, $User = Dan, and $Approver1 = Mike)
line 2 is($Fulfiller = Tom, $Owner = my-group, $User = Dan, and $Approver1 = Mike)
Instead of starting at line 1 this is looping twice but with data from line 2
Like I said i’m new and learning, so I am most likely doing something wrong and I got lucky with my script below… lol
example that does work
foreach ($line in $input_csvfile)
{
$group = $line.Group
$user = $line.User
try
{
Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false
write-output "$user removed from: $group"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
If ($members -contains $user) {
Write-Host "$user exists in the group"
} Else {
Write-Host "$user does not exists in the $group"-ForegroundColor red
}
}
catch
{
write-output "$_"
}
}
I also understand that most of this is written outside of the actual loop, for learning purposes I have always created custom objects because that is how I was taught.
found the issue, thank you for all your time, it is very much appreciated!
You should define your variables within your foreach loop. This is why you are seeing everything as the final entry in the CSV file - you might’ve run it once and if your re-using the same runspace it will have values in $line already to populate your variables at the top
So reflowing this to work correctly - it would look like this
error im getting is below:
Unrecognized database format ‘C:\Users\XXXXXX\Desktop\Group_Access_Powershell_export.accdb’.At
Z:\filepath here
Generation.ps1:78 char:5