Etika49
Etika49

Reputation: 752

Powershell get lastlogonDate of all servers in OU

I am trying to get the last logonDate of all servers in OU with Powershell.

My script is able to collect the data but unable to write it to the csv report. (The current version populates only the Server name and not the OS and LogonDate fields in the csv file) Need help with adjusting the output and if you can suggest improvements would also be great

$allservers = get-adcomputer -filter * -searchbase "ou=important, ou=Member Servers, dc=contoso, dc=com" | select-object -expand name
$File = "$(Get-Date -Format ddMMyy_HHmmss)"

foreach ($server in $allservers) {
    Get-ADComputer -Identity $server -Properties * | format-table Name, LastLogonDate, OperatingSystem 
    $Props = [ordered]@{
        ServerName      = $server
        OperatingSystem = $server.OperatingSystem
        LastLogonDate   = $server.LastLogonDate
    }

    $Obj = New-Object psobject -Property $Props
    $obj | Export-Csv -Path .\$File.csv -NoTypeInformation -Encoding UTF8 -Append
}

Upvotes: 2

Views: 749

Answers (1)

Cbsch
Cbsch

Reputation: 1224

I suspect you think that the first call in the foreach block is actually doing something with the $server variable. You are indeed loading all the properties from AD, but they are only printed to the console with Format-Table, not assigned to $server.

If you change second Get-ADComputer call to this, it will work. Replace

Get-ADComputer -Identity $server -Properties * | format-table Name, LastLogonDate, OperatingSystem

with this:

$server = Get-ADComputer -Identity $server -Properties * 
$server | format-table Name, LastLogonDate, OperatingSystem 

However, I would probably replace the entire thing with this, which will do the same:

$File = "$(Get-Date -Format ddMMyy_HHmmss)"
Get-ADComputer -Filter * -SearchBase "ou=important, ou=Member Servers, dc=contoso, dc=com" -Properties LastLogonDate,OperatingSystem | 
    Select-Object DistinguishedName, LastLogonDate, OperatingSystem | 
    Export-Csv -Path .\$File.csv -NoTypeInformation -Encoding UTF8

Upvotes: 2

Related Questions