RayDar RayDar - 3 months ago 32
PowerShell Question

Check a PowerShell script line against a txt file containing computer names

I need to check the following code against a txt file with computer names, so if the computer name exist in the file, it'll be copied to the shadow group.

$OU="OU=Computers,DC=mylab,DC=local"
$ShadowGroup="CN=SelectPCs,OU=Groups,DC=mylab,DC=local"
Get-ADComputer –SearchBase $OU –SearchScope OneLevel –LDAPFilter "(!memberOf=$ShadowGroup)" | ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup}


I tried a pipe and 'Where', but couldn't make it work:

$OU="OU=Computers,DC=mylab,DC=local"
$ShadowGroup="CN=SelectPCs,OU=Groups,DC=mylab,DC=local"
$PCList = c:\scripts\computernames.txt
Get-ADComputer –SearchBase $OU –SearchScope OneLevel –LDAPFilter "(!memberOf=$ShadowGroup)" **| Where-Object {$_.Name –Match $PCList}** |ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup}

Answer

I suggest you rewrite your command as follows:

Get-Content c:\scripts\computernames.txt | Get-ADComputer -Property MemberOf | 
   Where-Object { $_.DistinguishedName -match ('^[^,]+,' + $OU) -and 
                  $_.MemberOf -notcontains $ShadowGroup } |         
    ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup}
  • Start with your list of computer names, which Get-ADComputer should be able to identify directly, via the pipeline, implicitly bound to the -Identity parameter.

  • -Property MemberOf ensures that the non-default property MemberOf is included in each return object.

  • The Where-Object call then checks whether the computer is in the right OU ($_.DistinguishedName -match ('^[^,]+,' + $OU) - perhaps you don't even need this, given that you've identified the computers by name) and whether it's not already a member of $ShadowGroup ($_.MemberOf -notcontains $ShadowGroup).

  • Finally, the Foreach-Object calls adds the matching computers to group $ShadowGroup.