There are a few reasons why this doesn't work:
- You run Get-ADOrganizationalUnit before populating the variable "ou"
- You use Select-Object to populate the $search variable. This places a PSCustomObject into the $search variable, not the distinguishedname as you thought it would. To use the name of the OU in the -SearchBase parameter you'd have to use it in this way: $search.distinguishetname
There is another problem, too. You don't check to see if the Get-ADOrganizationalUnit actually found the OU, or if there were multiple OUs with similar names.
I think this is closer to what you intended:
$ou=read-host -prompt 'Please enter OU your computers reside in and we will create that for you'
Write-host "You have chosen $ou, processing now"
$search=Get-ADOrganizationalUnit -filter 'name -like "$ou"' | select DistinguishedName # creates a PSCustomObject
$search = (Get-ADOrganizationalUnit -filter 'name -like "$ou"').DistinguishedName
if ($null -eq $search -OR $search -is [array]){
Write-Host "Either $ou was not found or multiple OUs were found"
Write-Host "Please try again"
return
}
#Generate the list of computers
Get-ADComputer -Filter * -SearchBase $search |
Select-Object Name |
Export-CSV c:\users\$env:usersname\desktop\computers.csv
The $computers variable is never referenced in your code so I left it out of the answer. Also, if the file "computers.csv" is really a CSV it'll have a "header" as the first line and it will be part of the data. Did you mean to use Import-CSV where you've used Get-Content?