Improve company productivity with a Business Account.Sign Up

  • Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 45
  • Last Modified:

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

Jose Colmenares
Jose Colmenares
1 Solution
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.
Jose ColmenaresAuthor Commented:
You're the best. You solved and contributions more than my question and understanding. Thank you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now