Need help with error handling and nesting AD queries inside foreach loop

Here's what I'm trying to do...

Get computer names from an OU using Get-ADComputer
Get logged on user with computer name obtained from Get-ADComputer, use error handling to determine which computers weren't reachable.
If possible, Nest the fields below
Get-Adcomputer - "Full Name, Department"
Get-WMIobject - "Computer, Model"

I've tried with the script below but can't figure out how to nest or get the try-catch error handling to work.

Clear-Host

$Computers = Get-ADComputer -Filter * -SearchBase "DC=domain,DC=com" | select -ExpandProperty Name
 
Foreach ($Computer in $Computers){

    try{
        Get-WmiObject -Class win32_computersystem -ComputerName $Computer  -ErrorAction stop  | Select Username, Caption, Model
    }
    Catch{
        $Exception = $_
        If ($Exception.Exception.Message -like "The RPC server is unavailable*")
            {
                Write-Host -BackgroundColor Red "$_ was not reachable"
            }
    }


}
Pedro RiveraAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

oBdACommented:
Try this:
$CsvFile = 'C:\Temp\ComputerReport.csv'
Get-ADComputer -Filter * -SearchBase "DC=domain,DC=com" -Property Department | ForEach-Object {
	$ADComputer = $_
	Write-Host "Processing $($ADComputer.Name) ..." -ForegroundColor White -NoNewline
	Try {
		$CS = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ADComputer.Name -ErrorAction Stop | Select-Object -Property `
			@{n='Computername'; e={$ADComputer.Name}},
			@{n='DNSHostName'; e={$ADComputer.DNSHostName}},
			@{n='Department'; e={$ADComputer.Department}},
			Username,
			Manufacturer,
			Model
		Write-Host " OK ($($CS.Manufacturer) $($CS.Model))." -ForegroundColor Green
		$CS
	} Catch {
		Write-Host " ERROR: $($_.Exception.Message)" -ForegroundColor Red
		$_.Exception.Message | Select-Object -Property @{n='Computername'; e={$ADComputer.Name}}, @{n='Error'; e={$_}}
	}
} | Select-Object Computername, DNSHostName, Department, Username, Manufacturer, Model, Error |
	Export-Csv -Path $CsvFile -NoTypeInformation

Open in new window

0
Pedro RiveraAuthor Commented:
Hi oBdA, Thanks for the quick turn around on this I really appreciate it. Everything works great but I need to get the department of the user and not the computer. Sorry if my explanation was not well stated. Going to try on my own with what you've provide but if you have time see if you can help out with this one last thing.

Script is great!!!
0
oBdACommented:
Can't test it at the moment, but should work:
$CsvFile = 'C:\Temp\ComputerReport.csv'
Get-ADComputer -Filter * -SearchBase "DC=domain,DC=com" | ForEach-Object {
	$ADComputer = $_
	Write-Host "Processing $($ADComputer.Name) ..." -ForegroundColor White -NoNewline
	Try {
		$CS = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ADComputer.Name -ErrorAction Stop | Select-Object -Property `
			@{n='Computername'; e={$ADComputer.Name}},
			@{n='DNSHostName'; e={$ADComputer.DNSHostName}},
			@{n='Department'; e={
				If ($_.Username) {
					Try {(Get-ADUser -Identity $_.Username.Split('\')[1] -Property Department -ErrorAction Stop).Department} Catch {"ERROR: $($_.Exception.Message)"}
				}
			}},
			Username,
			Manufacturer,
			Model
		Write-Host " OK ($($CS.Manufacturer) $($CS.Model))." -ForegroundColor Green
		$CS
	} Catch {
		Write-Host " ERROR: $($_.Exception.Message)" -ForegroundColor Red
		$_.Exception.Message | Select-Object -Property @{n='Computername'; e={$ADComputer.Name}}, @{n='Error'; e={$_}}
	}
} | Select-Object Computername, DNSHostName, Department, Username, Manufacturer, Model, Error |
	Export-Csv -Path $CsvFile -NoTypeInformation

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Pedro RiveraAuthor Commented:
Thank you very much oBdA for the script. It worked perfectly.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.