0

I have a PowerShell script that's pulling computer information based on a CSV from the 'computer' column. From that information I'm trying to query related info from two sources.

One is a text file that shows a logon timestamp, the other is the lastlogondate from AD. I'd like to get the results together to output in a CSV.

I can't figure out how to combine the results. The separate commands are put into the $table variable, but that's obviously not correct.

So what I'm trying to end up with is a CSV with

Computer,LastWriteTime,LastLogonDate
PC01,lastwritetime,ADLastLogonDate

I'm thinking the solution would be to write the values to variables independent of each other, then put them into the $table variable together? But I'm not sure how to do that.

$computerList = Import-Csv $path

$table = @()

foreach ($line in $computerList) {
    $compName = $line.computer

    # Get the LastWriteTime from the network drive
    $table += Get-ChildItem *"$compName"* -Path R: |
              sort LastWriteTime |
              select LastWriteTime, Name  -Last 1

    # Get the lastlogondate from Active Directory
    $table += Get-ADComputer $compName -Properties Name, LastLogonDate |
              select Name,LastLogonDate
}

$table | Export-Csv "file.csv"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Andelas
  • 2,022
  • 7
  • 36
  • 45

1 Answers1

3

Untested

$computerList = import-csv $path
$table = @()
$table = foreach($line in $computerList){
    [pscustomobject]@{
        Computer      = $line.computer
        LastWriteTime = get-childitem -Path R: "*$compName*"|
                          sort LastWriteTime -descending|
                          select -ExpandProperty LastWriteTime -first 1
        LastLogonDate = get-adcomputer $compName -properties Name,LastLogonDate|
                          select -ExpandProperty LastLogonDate
    }
} 
$table | out-gridview
# $table | export-csv "file.csv"

Edited again according to the suggestions.

  • 1
    I see no reason why this wouldn't work, but you could skip `$obj=` and just do `$table+=[pscustomobject][ordered]@{...}` to simplify things. – TheMadTechnician Mar 22 '17 at 20:55
  • @TheMadTechnician thanks for the hint, I'll incorporate that. –  Mar 22 '17 at 21:22
  • 1
    My suggestion would be to do `$table = foreach($line in $computerList){ [pscustomobject][ordered]@{...}}` or do an array add. [With the `+=` you are destroying and recreating `$table` on each loop.](http://stackoverflow.com/questions/14620290/powershell-array-add-vs) – BenH Mar 22 '17 at 21:24
  • 2
    The `[pscustomobject]` type accelerator already uses an ordered hashtable, IIRC, so the explicit `[ordered]` accelerator shouldn't be required. And you may want to expand time/date properties. – Ansgar Wiechers Mar 22 '17 at 22:04
  • That's great. Worked perfectly. Thank you much. Wouldn't have even thought to lookup the possibility of a custom object. – Andelas Mar 23 '17 at 16:07