Todd Welch
Todd Welch

Reputation: 1779

How to add computers to a distribution group using powershell

I have created the code below and I am not figuring out who it is not working. If I do this manually it works but what seems to be the problem is that my variable is not going into the for-eachobject as an array and the entire contents of the variable is being used instead of one computer name at a time.

Any help would be greatly appreciated.

import-module activedirectory
$virtuals = get-adcomputer -filter "Name -like '*v'" | foreach-object{$_.distinguishedname}
foreach-object -inputobject $virtuals {
     Add-ADGroupMember VMs "$_"
}

The error I get is:

Add-ADGroupMember : Cannot find an object with identity: 'CN=CSD-024V,OU=VM,OU=Workstations,OU=...
' under: 'DC=co,DC=****,DC=wi,DC=us'.
At line:4 char:22
+     Add-ADGroupMember <<<<  VMs "$_"
    + CategoryInfo          : ObjectNotFound: (CN=CSD-024V,OU=...ark,DC=wi,DC=us:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
    + FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

Upvotes: 0

Views: 183

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

That is what's happening. Consider:

PS D:\> $nums = 1..5

PS D:\> $nums | ForEach-Object { "* $_ *" }
* 1 *
* 2 *
* 3 *
* 4 *
* 5 *

PS D:\> ForEach-Object -InputObject $nums { "* $_ *" }
* 1 2 3 4 5 *

I don't know why that distinction exists, but it is documented in the help, here:

When you use the InputObject parameter with ForEach-Object, instead of piping command results to ForEach-Object, the InputObject value is treated as a single object. This is true even if the value is a collection that is the result of a command, such as -InputObject (Get-Process).

So your fix would be:

$virtuals | ForEach-Object {
     Add-ADGroupMember VMs "$_"
}

Auto-generated PS help links from my codeblock (if available):

Upvotes: 1

Related Questions