2

I am trying to create a PowerShell script that takes a list from an array of partial machine names and return them to me

So far, I've imported ActiveDirectory module and setup the array. I then run a foreach against the array but it doesn't return any results, instead going to a new line.

I have tried assigning the Get-ADComputer line to a variable and calling the variable. I have also tried to use the Return and not achieved my results.

The results can just print out in a list on the screen, that's OK. I just need it to return the results and then I can build up from that.

This is what I have done so far:

$getPC = @("7477", "7473", "7474")
foreach ($i in $getPC)
{
    Get-ADComputer -filter {name -like "*$i*"} | select name
}

When I run the Get-ADComputer line alone, and put in the positional parameter, I have no problems. Any ideas?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Danijel-James W
  • 1,356
  • 2
  • 17
  • 34

1 Answers1

2

Even though the practice is widespread, do not use script blocks ({ ... }) as the -Filter argument.

Construct your -Filter as a string, which is the -Filter parameter's actual type; you'll avoid many obscure problems if you construct it as such.

So, instead of:

-Filter { Name -like "*$i*" } # WRONG - do not use { ... }

use:

-Filter "Name -like '*$_*'" # OK - use of a string

For an explanation, see this answer of mine.


As an aside, you could simplify your command somewhat using a single pipeline with the ForEach-Object cmdlet, in whose script block the automatic $_ variable (alias name: $PSItem) represents the input object at hand:

"7477", "7473", "7474" |
  ForEach-Object { Get-ADComputer -Filter "Name -like '*$_*'"} |
    Select-Object Name

Regarding your original command: As Seth recommends, it's better to use a more descriptive loop variable name than $i, such as $computer.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Oops! Thanks, @Seth, indeed my mistake. I've fixed the answer and also restructured it for clarity; I've also added your recommendation re naming the loop variable, so we can clean up the comments here. – mklement0 Mar 09 '18 at 10:59