0

I have a text file (file1.txt) with records in different lines
Variable1,2018
Variable2,Jun

Now in my script I would like to store the values in different variables. Example, I would like my end result to be Year=2018 Period=Jun

I tried the below logic but it is not solving the purpose as it is storing both values in a single variable.

 Get-Content "file1.txt" | ForEach-Object {
 $Var=$_.split(",")
 $Year=$Var[1]
 $Period=$Var[1]
 }

Please help.

2
  • Show some more contents of your file1.txt. Commented Jun 20, 2018 at 8:15
  • Give an example of you file in input and result file you hope Commented Jun 20, 2018 at 8:15

3 Answers 3

1

You can do Something like this, if you want use variable :

$Object=(Get-Content C:\Temp\test.txt).Replace(',', '=') | ConvertFrom-StringData
$Object.Variable1
$Object.Variable2
Sign up to request clarification or add additional context in comments.

Comments

1

You could do it using a hash like so:

$h = @{}
Get-Content "file1.txt" | % {
  $var = $_.split(",")
  $h[$var[0]] = $var[1]
}

$h['Variable1']

Or you could use an object like this:

$o = New-Object psobject
Get-Content "file1.txt" | % {
  $var = $_.split(",")
  $o | Add-Member -MemberType NoteProperty -Name $var[0] -Value $var[1]
  $h[$var[0]] = $var[1]
}

$o.Variable1

Comments

1

Why not use the new-variable cmdlet?

#get content from your file instead
$str = "Variable1,2018","Variable2,Jun"

foreach ($line in $str)
{
    $line = $line.split(",")
    New-Variable -name $line[0] -Value $line[1]
}

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.