Powershell Script to pull domain computers from a .txt list using a variable

STANWICK, JERALD 0 Reputation points

I have a powershell script below. I have a computers.txt file I have with part of computer names on network. The data in the .txt files contains numbers, example 72566 and 102222. I am using the wildcards below $Computers to search for the domain computers as in our domain the computer names are for example QAZ72566DFG. So wanting to look at the .txt file for the number and then the script looking for that info with the wildcards then output the complete computer names to the computersfound.txt file.

If I only add one number, for example, 72566 in the .txt file the script works and pulls that full machine name into the output file. However, if enter more than one number in the .txt file, it returns nothing (no errors just 0 output). Any help on returning more than one entry? Trying to return all retired computers to remove from AD into the computersfound.txt file. Right now only can have one issue. I think if add more than one number is it looking at that as one entry for not finding anything? If so how to have it look at each entry in the .txt file separately? Here is the script.

$Computers = Get-Content c:\ADClean\computers.txt

ForEach ($Computer in $Computers)

{ $ADComputer = $null

$ADComputer = Get-ADcomputer -Filter * | Where-Object {$_.Name -like "$Computers" } | Select -Property Name | export-csv c:\ADClean\computersfound.txt -notypeinformation


A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,146 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 45,111 Reputation points

    Your problem is that you're using the variable $Computers instead of $Computer (without the 's') in the Where-Object cmdlet.

    You can also do it this way, using wildcard characters in the "-like" comparison:

    Get-Content c:\ADClean\computers.txt |
        ForEach-Object {
            $Computer = $_.Trim()           # remove an leading or trailing whitespace
            Get-ADcomputer -Filter * | 
                Where-Object {$_.Name -like "*$Computer*" } | 
                    Select-Object -Property Name
    } | export-csv c:\ADClean\computersfound.txt -notypeinformation
    0 comments No comments