powershellcsvforeachactive-directoryimport-csv

Powershell pipeline objects from import-csv headaches


We have a big audit coming up, and we want to be sure that all termed employees' AD computer accounts have been deactivated. I have a .csv that has a unique identifier that we use - our schema includes that ID in the middle of the ADcomputer Name property. I am having enormous trouble correctly piping the imported csv objects and their property to the filter. I think. I'm not entirely sure. This is something like what I've been trying.

Import-Csv termname.csv | ForEach-Object
{ Get-ADComputer -Filter { Name -Contains "$($_.id)" } } |
Export-Csv termcomp.csv -NoTypeInformation

This "script" pulled a total of no content, while I KNOW that when I test

Get-ADComputer -Filter { Name -Contains $id } 

where $id is that unique ID, I get hits on AD Computer objects. Likewise, testing this block

Import-Csv termname.csv | ForEach-Object { Get-ADComputer { Name -Contains $_.id } 

PowerShell's error is:

..."Property 'id' not found in object of type: 'System.Management.Automation.PSCustomObject'.

I think that I am misapprehending what precisely is an "object" in this case. Is the whole imported array an object, with a property of .id? Or is each row its own object, with a .id property? And, either way, why has PowerShell such strong objections to a pipeline object, which is, after all, its primary job?

Is there an entirely better way to go about this whole process? Am I somehow overthinking the whole mess?

UPDATE

As requested, sample contents of the csv file. Taking the suggestion to use wildcards instead, I've put the wildcards into the .csv itself, which, again, may not be the most elegant solution. But as long as it works! Here's the sample, copied from Notepad++

id
*rstarr56*
*jlennon58*
*pmcartney74*
*gharrison68*

Solution

  • After hours of digging, I found an answer here:

    Import-CSV and Foreach to use Get-ADUser

    Thanks especially to Mike for some great thinking about -Like and how to test the success of the code.

    The line that ended up working was:

    Import-Csv termname.csv | ForEach-Object {
       Get-ADComputer -Filter "Name -Like '*$($_.id)*'"
    } | Export-Csv termout.csv
    

    Apparently, Powershell hates {{}}.

    Thanks again, all!