0

I have a csv with columns that contain a user's first name last name. I have firgured out how to import the csv data from each column using:

$firstname = Import-csv .\data.csv | select-object "Employee First Name" 
$lastname = Import-csv .\data.csv | select-object "Employee Last Name"

I have also figured out that:

$username=$firstname.substring(0,1)+$lastname 

works when using system.string objects. The problem is I need to loop through all of names to create a new column with the username and I get the error

System.Object[]] doesn't contain a method named 'substring'

I thought I could convert to string using $firstname.ToString() but I seem to have botched that. Any help is geatly appreciated as I am still trying to learn powershell.

2 Answers 2

1

The error is self expressive $firstname is not a string. $firstname is an array of string.

Try :

$username = ($firstname[0]).substring(0,1)+$lastname[0]

you'd better use :

$employees = Import-csv .\data.csv
foreach ($employee in $employees)
{
  $username=($employee.'Employee First Name').substring(0,1)+($employee.'Employee Last Name')
}
Sign up to request clarification or add additional context in comments.

Comments

0

Looks like you are trying to make a user name. So i'm not sure why you want to import one column at a time?

But this might work for you.

$names = Import-Csv .\test.csv
$userNames = New-Object 'System.Collections.Generic.List[String]'

foreach ($name in $names)
{
    $userNames.Add($($name.firstName.Substring(0,1) + $name.lastName))
}

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.