We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Powershell - Foreach Statement Error

Medium Priority
94 Views
1 Endorsement
Last Modified: 2020-04-05
I am encountering a weird error and its boggling my mind. Can you powershell experts please show me what i am doing wrong. I am trying to put together a foreach statement that will readd AD groups to an AD User object/Member. So whats odd is that if i used the below PS code it works manually but does not work with variables and the foreach code below. It errors our stating cant find identity. But why when i manually input the same identity that is looping through it errors our. So for example if i type:

Add-ADGroupMember - OPSC -Members 1078477

Open in new window


It works just fine.. I verify and the AD Group is added to member 1078477

But when i insert this with variables and a foreach statement it states it cant find the identity? I verify that whats looping through is correct by executing the variable by itself.

$adgroups = Get-Content -Path C:\Scripts\adgroups.txt
foreach ($group in $adgroups) { Add-ADGroupMember - $group -Members 1078477}

Open in new window


Ive been playing with foreach statements all day trying to finetune my PS skills and understand the difference between foreach and Foreach-Object and Get-Content and Import-CSV for my own knowledge.

foreach-statement-erro.pngadgroups.png
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
With this syntax, you should actually get something like "Add-ADGroupMember : A positional parameter cannot be found that accepts argument 'OPSC '.", because you're not naming the "Identity" argument, you just have a minus there.
In addition (can't tell from the screenshot), verify that you don't have trailing spaces in your text file. When you paste it like that into a command prompt, the space will be ignored, because you didn't put quotes around it. When you process a list read from a file containing trailing spaces, the space will be expected.
Or trim the input, just to be sure:
$adgroups = Get-Content -Path C:\Scripts\adgroups.txt | ForEach-Object {$_.Trim()}
foreach ($group in $adgroups) {Add-ADGroupMember -Identity $group -Members 1078477}

Open in new window

But when you want to add multiple groups to the same AD user, it's better to use Add-ADPrincipalGroupMembership:
$adgroups = Get-Content -Path C:\Scripts\adgroups.txt | ForEach-Object {$_.Trim()}
Add-ADPrincipalGroupMembership -Identity 1078477-MemberOf $adGroups}

Open in new window

Isaias PerezIT Operations Manager

Author

Commented:
Oh no I'm sorry. I must have mistype'd, i did have -identity followed by the variable $group. I have never heard of trim. More than just making this work i really want to learn and understand this level of powershell and why something doesn't work. Why would it work if i typed out

Add-ADGroupMember -identity "OPSC" -Members 1078477    (Works fine)

Open in new window


But then would not work when i am passing the same data in the variable along with other AD Group Aliases.

$adgroups = Get-Content -Path C:\Scripts\adgroups.txt
foreach ($group in $adgroups) { Add-ADGroupMember -Identity $group -Members 1078477}

Open in new window


Error I get:

Add-ADGroupMember : Cannot find an object with identity: 'OPSC                                              ' 
under: 'DC=contoso,DC=net'.
At C:\Scripts\READD AD Groups.ps1:2 char:33
+ ...  in $adgroups) { Add-ADGroupMember -Identity $group -Members 1078477}
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (OPSC           ...               :ADGroup) [Add-ADGroupMember], 
    ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundExc 
   eption,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

Open in new window


Really odd to me but i appreciate your help with this. Ill try to play with the ad-addprincipalgroupmembership instead and see if it gives me the same error. Furthermore learn the (.)syntax and when or where to use it and what they are   {$_.Trim()}
Isaias PerezIT Operations Manager

Author

Commented:
I did notice that on your example, after you have defined the $adgroups variable, you pipe it through to the rest of the code and I am not.
code-error.png
Isaias PerezIT Operations Manager

Author

Commented:
By incorporating .trim() worked on the code. So i am assuming them that unwanted characters are being piped through and thus the trim is getting rid of that. Only 1 AD group failed but the rest worked.

$adgroups = Get-Content -Path C:\Scripts\adgroups.txt 
foreach ($group in $adgroups) { Add-ADGroupMember -Identity $group.trim() -Members 1078477}

Open in new window


I am also assuming that for the foreach statement, you dont have to pipe through the variable but for the ForEach-Object you do?
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Isaias PerezIT Operations Manager

Author

Commented:
Thank you so much oBdA. I sincerely appreciate your patience and instructions. I wish i can pay ya for private instruction.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.