Question

I am running to an issue with a Powershell command line I'm attempting to run. What we are needing is to get the PC Name and LastLogonDate from PC's in a list of text files with Powershell.

Here is the code I'm attempting to run:

Get-Content C:\Hosts.txt | ForEach-Object{Get-ADComputer $_ -Properties Name,LastLogonDate | Select-Object Name,LastLogonDate | Export-Csv C:\Output.csv}

When I run that code I get an error stating: "Cannot find a object with identity: 'ComputerName'" despite the fact that the PC is truly in AD. What is confusing me is that everything after the ForEach-Object runs great if you run it by itself. When you add the Get-Content and ForEach-Object the errors begin. I can see from the error messages that each individual computer name is being read from the text file, but I wonder if it is passing it in a way the Get-ADComputer doesn't like.

Was it helpful?

Solution

A couple things. First is to see what's in the hosts.txt file. Second thing is to move the Export-Csv command outside of the ForEach-Object statement. If you leave it how it is, it will only return the last object it processed in the csv file. I've posted an example of how it should be.

Get-Content C:\Hosts.txt | ForEach-Object {Get-ADComputer $_ -Properties Name,LastLogonDate | Select-Object Name,LastLogonDate} | Export-Csv C:\Output.csv

I'm not able to replicate your problem and the only thing different is the contents of the hosts.txt file so it would be helpful to see it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top