Reputation: 573
I would like to retrieve some numbers from a text file using Windows PowerShell. Assume that I have a text file values.txt
that looks like this (I can modify it as I want):
foo=100
bar=-3
foobar=-15
asdf=-4
I would like to add a variable to my PowerShell script called $bar
that is equal to the number -3
, as the text file says it should be. How do I do this?
Upvotes: 0
Views: 4194
Reputation: 437121
Note: The input file looks like part of an *.ini
file; for more full-featured support of such files, consider a third-party module such as PSIni
.
As Matt suggests in a comment on the question, ConvertFrom-StringData
sounds like the right tool:
# Read the key-value pairs stored in file file.txt into [hashtable] $ht
PS> ($ht = Get-Content -Raw -LiteralPath file.txt | ConvertFrom-StringData)
Name Value
---- -----
foo 100
bar -3
foobar -15
asdf -4
# Access a specific value:
PS> $ht.foo # or: $ht['foo']
100
Note:
ConvertFrom-StringData
returns a hashtable rather than creating individual variables:
As shown above, you must access the foo
input line's value as $ht.foo
(or $ht['foo']
) rather than $foo
, for instance.
To ensure that only a single hashtable is created, Get-Content -Raw
(PSv3+) must be used to pass the entire input file as a single string.
ConvertFrom-StringData
only ever creates [string]
values, so if the input values should be treated as numbers, for instance, manual conversion is required:
# .Clone() is needed to support enumeration and modification in the same loop.
foreach($key in $ht.Keys.Clone()) { $ht.$key = [int] $ht.$key }
Generally, there are more subtleties to consider, such as \
rather than `
serving as the escape character and quotes getting retained as literals - see the docs.
Upvotes: 2
Reputation: 1922
This should work:
$file = "C:\test.txt"
foreach($line in (Get-Content $file)) {
$a = $line.Split("=")
New-Variable -Name $a[0] -Value $a[1]
}
Write-Output ""
Write-Output "Variable Check ::"
Write-Output "foo = $foo"
Write-Output "bar = $bar"
Write-Output "foobar = $foobar"
Write-Output "asdf = $asdf"
You can also put the name/value in different variables if you don't want to use an array, just change the for loop:
$a,$b = $line.Split("=")
New-Variable -Name $a -Value $b
Using Matts suggestion of ConvertFrom-StringData
:
$line = $line | ConvertFrom-StringData
New-Variable -name $line.Keys -Value $line.Values
hope this helps
Upvotes: 1