Link to home
Start Free TrialLog in
Avatar of David Schmalzer
David SchmalzerFlag for United States of America

asked on

Powershell

I am running the below powershell script to get last user logon times. The script runs and all the user info scrolls down the window and then actually creates the csv file, but there is no data in the file. Help.

Code:

clear
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 }

$Users = Get-ADUser -Filter *
Foreach ($auser in $Users)
{
      $MyName = $auser.SamAccountName
      Get-ADUserLastLogon -userName "$MyName"
}
$Lines | Out-File c:\fp\lastLogons.csv
Avatar of footech
footech
Flag of United States of America image

There are a few problems.  Chief among them is that $Lines is not defined anywhere and thus can't output anything to the file.
I notice that you're not using $hostname anywhere after it is defined.  I'm guessing you want to add it with the -Server parameter for Get-ADUser.  No idea why you're piping the output from Get-ADUser to Get-ADObject though.  Just specify lastlogon as a property you want to retrieve for the Get-ADUser command.
In your function you're only using Write-Host commands for output, which only outputs to the screen.  Use Write-Output instead if you want to be able to do anything else with the output of the function (like write it to a file).
The foreach statement doesn't send any output to the pipeline.  A work-around is surround the construct with subexpression or array notation (subexpression shown).
$(Foreach ($auser in $Users)
{
      $MyName = $auser.SamAccountName
      Get-ADUserLastLogon -userName "$MyName"
}) | Out-File c:\fp\lastLogons.txt

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of David Schmalzer

ASKER

Yes, that will work, thanks!