How to append error from Get-ADComputer to table?

I am trying to query multiple computers from the Domain using Get-ADComputer. I would like to append the pc name I queryed to the array with the word "error" or a nonsensical date or even a blank value in that spot.

Import-Module ActiveDirectory
$PCNames = "laptop-namea", "laptop-nameb", "laptop-badname"
$Output = @()
$Output = foreach ($PC in $PCNames) {
    try {
        Get-ADComputer -Identity $PC -Properties * |
            Select-Object Name, LastLogonDate
    } catch {
        $Output += ($PC)
    }
}

Current output:

Name         LastLogonDate        
----         -------------        
LAPTOP-NAMEA 1/27/2019 10:37:13 AM
LAPTOP-NAMEB 1/22/2019 8:23:02 AM 

Wanted/expected output:

Name           LastLogonDate        
----           -------------        
LAPTOP-NAMEA   1/27/2019 10:37:13 AM
LAPTOP-NAMEB   1/22/2019 8:23:02 AM 
LAPTOP-BADNAME 

2 answers

  • answered 2019-01-30 23:21 JosefZ

    Try - Catch - Finally blocks handle terminating errors. Apply the common parameter -ErrorAction -Stop as follows:

    Import-Module ActiveDirectory
    $PCNames = "laptop-namea","laptop-nameb","laptop-badname"
    $Output = ForEach ($PC in $PCNames) 
        {
            try{
                Get-ADComputer -Identity $PC -Properties * -ErrorAction Stop | 
                    Select-Object Name, LastLogonDate
                } 
            catch{
                [PSCustomObject]@{Name=$PC;LastLogonDate=$null}
                }
        }
    

  • answered 2019-01-30 23:37 Ansgar Wiechers

    Use -Filter instead of -Identity to avoid throwing errors in case of invalid names.

    $Output = foreach ($PC in $PCNames) {
        New-Object -Type PSObject -Property @{
            'Name'      = $PC
            'LastLogon' = Get-ADComputer -Filter "Name -eq '$PC'" -Property LastLogonDate |
                          Select-Object -Expand LastLogonDate
        }
    }
    

    Beware that querying AD for each individual computer is time-consuming. If the number of queries grows beyond a certain point it's better to query all computers, put them into an appropriate data structure (usually a hashtable), and then look up the desired information in that data structure.

    $computers = @{}
    Get-ADComputer -Filter '*' -Property LastLogonDate | ForEach-Object {
        $computers[$_.Name] = $_.LastLogonDate
    }
    
    $Output = foreach ($PC in $PCNames) {
        New-Object -Type PSObject -Property @{
            'Name'      = $PC
            'LastLogon' = $computers[$PC].LastLogonDate
        }
    }