3

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?

1
  • So what do you want $out to be? A custom object? A multidimensional array where each object in the array is another array with a set of values? Commented Mar 1, 2013 at 13:17

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.