0

I have an interesting problem. I've created a function to get all the users in an OU and check the last time they logged into to any one of the domain controllers. Now my problem is, i get the correct output in the powershell window, I just cant seem to get the output into a txt or csv file. Any help would be much appreicated

$currentdate = Get-Date
$currentdate | Out-File report.txt -Append

function Get-ADUserLastLogon([string]$userName,$array,$datetime)
 {
  $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 "`n"
}

$users = get-aduser -filter * -SearchBase "ou=Example,dc=Adatum,dc=co,DC=nz" -pr DistinguishedName
$i = 0

write-host "Getting all users in $ou"

while($true)
{
    $i++
    Get-ADUserLastLogon -UserName $users[$i] -array $i
        if($users[$i] -eq $null)
        {
        break
        }
    $usrindex = $i
    $dt | out-file report.txt -Append
    $username | out-file report.txt -Append
}
  • Answered before (in several ways): http://stackoverflow.com/questions/5588689/redirect-write-host-statements-to-file – PaulG Apr 23 '15 at 22:19
  • Check your code, it seems a bit fishy. You are not using $hostname anywhere, why loop over $dcs at all then? – Erti-Chris Eelmaa Apr 23 '15 at 22:19

1 Answers1

0

In your function, create an array of objects, where each object is of type System.Object and has properties of type NoteProperty and named after UserName, LastLogon etc. you can then export that array to a CSV easily. See my answer to the following question for an example : How to use two echo commands to print data on one line using PowerShell

Community
  • 1
  • 1
Graham Gold
  • 2,435
  • 2
  • 25
  • 34