Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating an Object from a text file

Status
Not open for further replies.

aminmgh

Technical User
Oct 31, 2012
1
0
0
US
Hi guys!
I've just started learning Powershell and I'm really newbie at it! so sorry for that

but i have a big problem! this is my scenario:

I've created a text file that contains some first names and last names that has been separated by space like this:
Jack Nicholson
Tom Cruise
.
.
I want to create an object with this in order to add multiple users in A.D
I used these commands:
$array = get-content name.txt | foreach (
>>$name = @{}
>>$name.first , $name.last = $_.Split()
>>$name
>> )

But i received this error:
Missing closing ')' in expression.
At line:3 char:1
+ <<<< $name.first , $name.last = $_.Split()
+ CategoryInfo : ParserError: (CloseParenToken:TokenId) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInExpression


can you help me please? what's the problem ? what should i do?

 
Here is a working example:

names.ps1
Code:
# run:
# powershell -ExecutionPolicy RemoteSigned .\names.ps1 

$my_file = get-content .\names.txt

echo "* Using string split function:"
foreach($line in $my_file){
  # split line into array
  $line_arr = $line.split()
  # array elements
  $first_name = $line_arr[0]
  $last_name = $line_arr[1]
  echo "first name: '$first_name', last name: '$last_name'"
}

echo ""

echo "* Using regex split function:"
foreach($line in $my_file){
  # split line into array
  $line_arr = [regex]::split($line,"\s+")
  # array elements
  $first_name = $line_arr[0]
  $last_name = $line_arr[1]
  echo "first name: '$first_name', last name: '$last_name'"
}

Output:
Code:
C:\Work\PowerShell>powershell -ExecutionPolicy RemoteSigned .\names.ps1
* Using string split function:
first name: 'Jack', last name: 'Nicholson'
first name: 'Tom', last name: 'Cruise'

* Using regex split function:
first name: 'Jack', last name: 'Nicholson'
first name: 'Tom', last name: 'Cruise'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top