How to read variable from file

I want to create a file when I define all constants which i will be used in my scripts. For example

$Path=c:\Windows\Ala

$Var1="Test"

$Var1="123123123"

How can I read this file from some PSscripts? How to import these constants from this file?

February 11th, 2015 11:33am

You can use Get-Content to read a file and then parse the content and assign variables any way you see fit.
Free Windows Admin Tool Kit Click here and download it now
February 11th, 2015 11:42am

If you create a file like this:

Name,Value
Path,c:\Windows\Ala
Var1,Test
Var2,123123123

You can use this code to create variables based on the data in the file.

Import-Csv -Path C:\ps\yourfile.csv | New-Variable

A couple things to note:

1. The variables will all be local in scope (see Get-Help about_Scopes for more info about that)

2. The variables will all contain string values. If you wanted to store a constant that was a number, it would be imported as the string version of that number.

February 11th, 2015 1:35pm

You can also place the variable assignment statements in a powershell script file, and dot-source it from within your main script, i.e.:

PS C:\Users\Al> type z1.ps1
write-host "before, [$path]"
. ./z2.ps1
write-host "after, [$path]"
PS C:\Users\Al> type z2.ps1
$Path="c:\Windows\Ala"
$Var1="Test"
$Var1="123123123"
PS C:\Users\Al> .\z1.ps1
before, []
after, [c:\Windows\Ala]

this will create the given variables in a scope that is local to the script. Also, unlike the other solutions presented, this method allows you to give the variables values other than simple strings, including numeric values, objects, etc.

Free Windows Admin Tool Kit Click here and download it now
February 11th, 2015 8:23pm

Sorry, I see now that you wanted constant values, not variables.

For that you could use the set-variable like this in the dot-sourced file:

    set-variable -name Path -option ReadOnly -value "c:\Windows\Ala"

February 11th, 2015 8:36pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics