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
}