PowerShell: How to Retrieve a Variable from a Text File


Often you may want to retrieve values from a text file and use them as variables.

You can use the following syntax to do so:

Get-Content team_info.txt | Foreach-Object {
    $myvar = $_.Split('=')
    New-Variable -Name $myvar[0] -Value $myvar[1]
}

This particular example gets the first value from each line in the file named team_info.txt and converts it into a variable whose value is equal to the value after the equal sign in each line.

Here is what the various commands do:

  • Get-Content: This retrieves all lines from the text file named team_info.txt
  • Foreach-Object: This specifies an action to perform on each line of the file
  • $my_var = $_.Split(‘=’): This splits each line based on where the equal sign occurs
  • New-Variable -Name $myvar[0] -Value $myvar[1]: This creates a new variable whose name is the first element that results from the split and whose value is the second element that results from the split

The following example shows how to use this syntax in practice.

Example: How to Retrieve Variables from a Text File in PowerShell

Suppose we have a text file named team_info.txt in our current directory.

We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to create variables from this file, using the first value in each line as the variable name and the value after the equal sign ( = ) as the value for the variable.

We can use the following syntax to do so:

Get-Content team_info.txt | Foreach-Object {
    $myvar = $_.Split('=')
    New-Variable -Name $myvar[0] -Value $myvar[1]
}

The following screenshot shows how to use this syntax in practice:

PowerShell retrieve variable from file

We can see that each line in the file has been converted into a variable with a specific value.

For example, when we type $location we can see that this variable exists with a value of Dallas.

When we type $team we can see that this variable exists with a value of Mavericks.

When we type $conference we can see that this variable exists with a value of West.

And so on.

Note that this example assumes each line in the file has the syntax variable=value.

If the variable and the value have a different separator between them in the file then you can specify this separator within the Split() method in the code.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if a Variable is Numeric
PowerShell: How to Split String into Separate Variables
PowerShell: How to Get String Length of Variable

Leave a Reply