Reputation: 15
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.
Upvotes: 0
Views: 135
Reputation: 754
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]
}
Upvotes: 1
Reputation: 11188
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
Upvotes: 1
Reputation: 17462
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
Upvotes: 1