0

I have a list of users in a CSV File that I want to find out if/when they last logged in. I can get this info for an individual account but I need to write this to a file for several accounts.

The error I'm getting:

At line:5 char:7 
import-module activedirectory
Missing = operator after key in hash literal
hash literal was incomplete

My Code:

$resultList = @()
Import-Csv C:\Users\admin\Desktop\SamAccountName.csv -header("SamAccountName") | Foreach-Object{
$user = ([adsisearcher]"(samAccountName=$($_.SamAccountName))").FindOne()
$resultList += New-Object -TypeName PSObject -Property @{
           SamAccountName = $_.SamAccountName

Import-Module ActiveDirectory
function Get-ADUserLastLogon([string]$_.userName)
{
  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $time = 0
  foreach($dc in $dcs)
  { 
    $hostname = $dc.HostName
    $user = Get-ADUser $userName | Get-ADObject -Properties lastLogon 
    if($user.LastLogon -gt $time) 
    {
      $time = $user.LastLogon
    }
  }
  $dt = [DateTime]::FromFileTime($time)
  Write-Host $username "last logged on at:" $dt }

Get-ADUserLastLogon -UserName $user
                        }
       }
}

$resultList | export-csv -Path c:\users\admin\desktop\SamAccountName_results.csv -NoTypeInfo
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
Heath Hackett
  • 47
  • 1
  • 9
  • 2
    It's telling you exactly what's wrong - you never closed the `@{` before doing the `Import-Module`. – Jeff Zeitlin Apr 04 '17 at 14:31
  • Possible duplicate of [Lastlogon from All Domain Controllers CSV output](http://stackoverflow.com/questions/41042336/lastlogon-from-all-domain-controllers-csv-output) – Bill_Stewart Apr 04 '17 at 14:32
  • Jeff you were right. It's now saying i'm missing a ')' on function get-aduserlastlogon ([string]$_.username) any thoughts? – Heath Hackett Apr 04 '17 at 15:21

1 Answers1

2

Instead of this:

$user = ([adsisearcher]"(samAccountName=$($_.SamAccountName))").FindOne()
$resultList += New-Object -TypeName PSObject -Property @{
           SamAccountName = $_.SamAccountName

Please do this:

$user = ([adsisearcher]"(samAccountName=$($_.SamAccountName))").FindOne()
$resultList += New-Object -TypeName PSObject -Property @{
           SamAccountName = $_.SamAccountName
           }
Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
  • I am getting this error. I have no idea what it means, and after reading this and three other similar answers, I still have no idea. I can't spot a difference between the top code and the bottom code. – bbsimonbb May 03 '22 at 10:03
  • @bbsimonbb: Add a curly brace close before your import module. The issue is because of it, the function is going inside the Object. – Ranadip Dutta May 03 '22 at 11:28