How I can consult this script for a CSV file?

I need to consult the following command to know the user logged for a group of 5000 computers in a csv file, I do not know how to join the import and the Foreach-Object. Can you help me?


The command work for 1 computer, I need consult for 5000 in a csv file.

 
$userlogged = Get-WmiObject -Class win32_computersystem -ComputerName "nameofcomputer" | select username

 $arr = $userlogged -split "\\"

 $user= $arr[1] -replace "}",""

 Get-ADUser $user -Properties * | select samaccountname, Name, description, office 

Open in new window


Thanks.
Jose ColmenaresAsked:
Who is Participating?
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:
This assumes that your csv contains a column "ComputerName" in which the names are listed.
Import-Csv -Path C:\Temp\computers.csv |
	ForEach-Object {
		$ComputerName = $_.ComputerName
		Write-Host "Processing $($ComputerName)"
		$(Try {
			$ConsoleUser = (Get-WmiObject -Query 'Select UserName From Win32_ComputerSystem' -ComputerName $ComputerName -ErrorAction Stop).Username
			If (-not $ConsoleUser) {Throw "No console user logged on!"}
			Get-ADUser -Identity $ConsoleUser.Split('\')[1] -Properties Description, Office -ErrorAction Stop | Select-Object -Property *
		} Catch {
			$_ | Select-Object -Property @{n='Error'; e={$_.Exception.Message}}
		}) | Select-Object @{n='ComputerName'; e={$ComputerName}}, SamAccountName, Name, Description, Office, Error
	} | Export-Csv -NoTypeInformation -Path 'C:\Temp\Results.csv'

Open in new window

And do AD and your network a favor and don't query AD for all user properties, when all you really need (besides the default set returned by the cmdlet) is 'Description' and 'Office'. It may be a bit more typing for you, but it is a lot less stress on AD.
2

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
Jose ColmenaresAuthor Commented:
You're the best. You solved and contributions more than my question and understanding. Thank you.
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.