Load variables from another powershell script

后端 未结 3 1360
陌清茗
陌清茗 2020-12-15 02:27

I have several scripts that could be reusing variables so I\'d like to isolate variables in their own Variables.ps1 script, i.e.

$var1 = \"1\"
$var2 = \"2\"
         


        
相关标签:
3条回答
  • 2020-12-15 02:59

    Just to ensure correctness ... try this... in main.ps1

    echo "Test"
    . .\Variables.ps1
    echo $var1
    echo $var2
    
    0 讨论(0)
  • 2020-12-15 03:00
    # var.ps1
    $Global:var1 = "1"
    $Global:var2 = "2"
    

    This works. Whether it's better or worse than "dot sourcing" probably depends on your specific requirements.

    PS > .\var.ps1
    PS > $var1
    1
    PS > $var2
    2
    PS >
    
    0 讨论(0)
  • 2020-12-15 03:06

    The variables declared in Variables.ps1 are at "Script Scope". That is you can not see them outside of the scope of the script that declares them. One way to bring the variables in Variables.ps1 to the scope of main.ps1 is to "dot source" Variables.ps1. This, in effect, runs Variables.ps1 at the scope of main.ps1. To do this, just stick a period and space before your invocation of the script:

    . .\Variables.ps1
    $var1
    $var2
    
    0 讨论(0)
提交回复
热议问题