get-content and foreach loop

Copper Contributor

Hi

I am trying to set  permissions  to all GPOs names in the file. I got the first PS script working by using -eq  to name of a GPO in the file, but i need to set permissions to all GPOs in the file .

I cant seems to figure it out  . what am i doing wrong? 

 

Thanks in advance for your help! 

 

First script  works just for one GPO

$gpos =Get-Content "D:\gpolist1.txt"

$gpos | foreach {

if ($_ -eq "test") { Set-GPPermission -PermissionLevel GpoEditDeleteModifySecurity -TargetName "GPOAdmins" -TargetType Group $_ }

}

 

Not working , need to set permissions  for all GPOs in the file

$gpos = get-content "d:\gpolist1.txt"
Write-Output $gpos

foreach ($gpo in $gpos) {
#call displayname
if ($_ -eq $gpos) {Set-GPPermission -PermissionLevel GpoEditDeleteModifySecurity -TargetName "GPOAdmins" -TargetType Group $_ }

else { write-output "no result" }

}
3 Replies

@DarrenRD 

Hi

Surely this won't be matching, 

You are comparing a single item to an array of items with will never match.

Also, please tell me more about this line

foreach ($gpo in $gpos) {

if ($_ -eq $gpos) {Set-GPPermission ...

You are checking each item from a text file you have and checking if each line (Item=$GPO) of the text is part of the $gpos.

Yes, sure it's all part you get the data from there.

I guess you need to check if each item $gpo name is exist between all other domain GPO.

 

$_ references the current item in the pipeline but not in a foreach loop.

Inside your foreach loop $gpo references each item loaded from the file.
So your if statement and Set-GPPermission should reference $gpo and not $_

@psophos @farismalaeb  TY you both! . your comments got me thinking  .. since my file may also contain non-exist GPOs in the domain i decided to use the Try and Catch. and seem  to be the only way i got it working!   see the screenshot 

 

DarrenRD_0-1625972489628.png