idarryl
idarryl

Reputation: 769

How to add/combine output to existing an array in PowerShell?

My $file contains two columns. Using the username in ., I would like to add name and givenname as the third and fourth columns respectively. So far I have:

$file = Import-Csv H:\computers2userswoSP1.csv
$out = foreach ($o in $file.name) {
    Get-ADUser $o | select name, givenname
}

I tried adding the code below into the first foreach, but that didn't work:

foreach ($r in $out) {
    New-Object PSObject -prop @{
        name = $file.fullname
        givenname = $file.Firstname
    }
}

and also adding this before the loops:

Add-Member -InputObject $file -TypeName fullname
Add-Member -InputObject $file -TypeName Firstname

with this in the loop:

$out.givenname += $file.FirstName
$out.name += $file.

As you can see, I'm shooting in the dark a little. Any recommendations?

Upvotes: 3

Views: 7665

Answers (2)

Shay Levy
Shay Levy

Reputation: 126712

Import the file, pipe to select, select all of its properties and add two more. This will create blank properties which you can update inside the loop.

The import command (Import-Csv) is in parentheses so you can update the file. Without it, the file will be in use and the update will fail.

One thing though. It looks like you already have a Name column in your file, so I named the new property 'fullname'.

(Import-Csv H:\computers2userswoSP1.csv | select *, Name, GivenName) | ForEach-Object{
    $user = Get-ADUser $_.name | select fullname, givenname
    $_.fullname = $user.name
    $_.givenname = $user.firstname
    $_
} | Export-Csv H:\computers2userswoSP1.csv

Upvotes: 2

BartekB
BartekB

Reputation: 8650

If I read your intentions correctly, you want to add two properties to each object produced by Import-Csv based on data from AD. If that is the case, you can do something like (here Import-Csv is emulated by ConvertFrom-Csv):

@'
username,fullname
bielawb,"Bartek Bielawki"
fasolaj,"Jas Fasola"
'@ | ConvertFrom-Csv | foreach {
    $AD = Get-ADUser -Identity $_.username
    New-Object PSObject -Property @{
        UserName = $_.username
        FullName = $_.fullname
        Name = $AD.Name
        GivenName = $AD.GivenName
    }
}

Data in CSV is irrelevant; if fields do not match the one you have in your CSV, just update values in the New-Object syntax.

Upvotes: 1

Related Questions