Please assist. I'm getting familiar with PowerShell but I'm struggling with this new script. I have a list of FQDN Hostnames. They can be in either 3 different domains (1 forest) or not present at all (e.g. in another forest).
I want a PowerShell script that outputs another txt file with hostname,found in <domain>
This is how far I have come but it's not doing much. Also, I'm not sure how the $_ works here as I found this piece of code as a solution for a similar use case.
Behind the # I placed some code I tried as well.
$dcs = @("xx.****.com","xx.***.com","xx.***.com") | % {
foreach ($hostname in (Get-Content C:\Scripts\hostnames.txt)){
$check = Get-ADComputer $hostname -Server $_ #$hostname #-Filter { DNSHostname -eq $hostname $_}
if($check){
write-host "$hostname found in $_"
}
else{
write-host "$hostname not found in any domain"
}}}
CodePudding user response:
The problems I see on your code is the use of Write-Host
which purpose is to output information to the host and it's output is not captured by default, if you want to output to a file you don't need to use it.
The other problem is the use Get-ADComputer -Identity $hostname
, if a computer is not found, which will happen since you're querying different domains, this will give you errors. In this case it would be better to use -Filter
or -LDAPFilter
since both don't produce any error on an object not found, both return $null
instead.
As for data export, I believe CSV is much more appropriate for data export instead of a text file, hence the use of Export-Csv
.
$domains = (Get-ADForest).Domains
Get-Content C:\Scripts\hostnames.txt | ForEach-Object {
$found = foreach($domain in $domains) {
$comp = Get-ADComputer -LDAPFilter "(DNSHostname=$_)" -Server $domain
# if this computer was found on this Domain
if($comp) {
# stop the loop here and return this object
return [pscustomobject]@{
ComputerName = $comp.Name
Domain = $domain
Status = 'Found'
}
}
}
# if a computer was found on the inner loop, return the object
# and continue with next computer
if($found) { return $found }
# if no computer was found, return this object
[pscustomobject]@{
ComputerName = $_
Domain = ''
Status = 'Not Found'
}
} | Export-Csv path/to/export.csv -NoTypeInformation
I realized later that since you already have FQDNs the following might be a better option, this one will target the specific Domain based on the FQDN, I'll leave it up to you to choose which one you want to try.
$ErrorActionPreference = 'Stop'
Get-Content C:\Scripts\hostnames.txt | ForEach-Object {
$name, $domain = $_.Split('.')
$out = [ordered]@{
ComputerName = $name
Domain = $domain
}
try {
$null = Get-ADComputer $name -Server $domain
$out['Status'] = 'Found'
}
catch {
$out['Status'] = 'Not Found'
}
[pscustomobject]$out
} | Export-Csv path/to/export.csv -NoTypeInformation