Andelas
Andelas

Reputation: 2052

Combine results from two lines for a table

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"

Upvotes: 0

Views: 597

Answers (1)

user6811411
user6811411

Reputation:

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.

Upvotes: 3

Related Questions