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?
Technology Tips and News
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?
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.
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.
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"