David Schmalzer
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([strin g]$userNam e)
{
$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
Code:
clear
Import-Module ActiveDirectory
function Get-ADUserLastLogon([strin
{
$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($
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Yes, that will work, thanks!
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).
Open in new window