简体   繁体   中英

Error Handling Issue with Get-ADComputer in a foreach loop

I am running into an error handling issue and have tried a lot of different attempts without much luck. I have a data set and am trying to compare it against AD. A machine may exist in the data set, but not in AD. I would like to retain that information in my end array, but am running into a terminating error:

Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException

$data = Import-Csv -Path .\data.csv
$cdata = @()
foreach ($data in $data) {
    foreach ($addata in (Get-ADComputer -Identity $data.Name -Properties LastLogonDate | Select-Object LastLogonDate)) {
        $combine = @{
            "Name" = $data.Name
            "LastPolicyRequest" = $data.LastPolicyRequest
            "LastLogonDate" =  $addata.LastLogonDate
        }
        $cdata += New-Object psobject -Property $combine
    }
}

Get-ADComputer (and other AD cmdlets) throw this exception when you try to get an object by identity that doesn't exist. Use the -Filter parameter to avoid this issue. Also, don't use the same variable for item and set ( $data in $data ).

$csv = Import-Csv -Path '.\data.csv'
foreach ($data in $csv) {
  $name = $data.Name
  foreach ($addata in (Get-ADComputer -Filter "SamAccountName -eq '$name'" -Properties LastLogonDate | Select-Object LastLogonDate)) {
    ...
  }
}

If you just want to add the last logon date to those records that are present in AD you could do something like this:

$cdata = Import-Csv -Path '.\data.csv' |
         Select-Object Name, LastPolicyRequest, @{n='LastLogon';e={
           Get-ADComputer -Filter "SamAccountName -eq '$($_.Name)'" -Properties LastLogonDate |
             Select-Object -Expand LastLogonDate
         }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM