0

I am trying to assign / divide a string out to assign them to variables. The length of each row is random so I am kinda at a loss. Thanks for the help.

-String-
Company 1
Employee 1
Employee 2
Employee 3
Company 2
Employee 1
Employee 2
Employee 3

I want to assign each line to a variable. $a = "company 1" $b = "employee 1" ect. The only stable variable in this string is each line of data is a different variable. The length of each line is unknown.

Thanks again!

1
  • Is there anything you have tried thus far? Your string is a newline delimeted string? And you want each value to be its own variable? What are you doing with this information as I am curious if there is a better way. But like my first question. What have you tried? Commented Oct 24, 2015 at 0:50

1 Answer 1

0

If you really need to create a distinct variable for each row of your string, then use New-Variable in a loop:

$str = 'Company 1
Employee 1
Employee 2
Employee 3
Company 2
Employee 1
Employee 2
Employee 3'

# to know how many variables were created we will put them into array
$variables = @()
$i = 0
foreach ($row in ($str -split [Environment]::NewLine)) {
  # create new variable from row's value
  New-Variable -Name "row$i" -Value $row
  # and create a member of array
  $variables += [pscustomobject]@{Name = "row$i"; Value = $row}
  $i++
}

Write-Host "Total: $i"

foreach ($var in $variables) {
  Write-Host $var.Name $var.Value
}

# now we can get value from a variable 
Write-Host $row1
# or from array
Write-Host $variables[1].Name $variables[1].Value

But to operate on a collection of items it is really simplier to use arrays and other collection types without creating a variable per item:

$rows = @()
foreach ($row in ($str -split [Environment]::NewLine)) {
  $rows += $row
}
Write-Host "Total rows: $rows.Count"
# get the first row
$rows[0]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.