【问题标题】:How do I share variables among scripts in Powershell?如何在 Powershell 中的脚本之间共享变量?
【发布时间】:2018-08-13 20:00:53
【问题描述】:

我很难在网上找到解决此问题的答案。

我有一个脚本,它按特定顺序运行我所有的其他脚本。

$x=0;
$z=0;
cd *file path* ;
.\filename1.ps1 ; write-host "$x text $z text";
.\filename2.ps1 ; write-host "$x text $z text";

在每个脚本中,我都有将变量 $x 或变量 $z 加 1 的选项

$a=Read-Host
if ($a -eq "Option One") {$x = $x+1}
elseif ($a -eq "Option Two") {$z = $z+1}
else {Write-Host "Not a valid option" ; .\filenameX.ps1}

问题是运行所有这些脚本的脚本无法识别变量的变化。我该如何解决这个问题?

【问题讨论】:

    标签: powershell variables scripting


    【解决方案1】:

    天真的答案是“点源”这些脚本,即使用运算符 .  调用它们

    使用.  会在调用者的 变量范围内执行脚本,因此$x 和$z 的顶级修改即使在.\filename1.ps1 和.\filename2.ps1 具有完成。

    # Note the `. ` preceding the file path - the space after "." is mandatory
    . .\filename1.ps1 ; "$x text $z text"
    . .\filename2.ps1 ; "$x text $z text"
    

    但是请注意,调用者可以看到在. 调用的脚本中创建或修改的所有顶级变量。

    有关 PowerShell 中变量作用域的更多信息,请参阅this answer。


    更好的封装选项是(a)输出修改后的值,或者(b)使用[ref]参数将引用变量传递给脚本 - 必须相应地声明和分配其参数。

    【讨论】:

    • 我相信我想通了。这是你的意思吗?共享脚本:return [PSCustomObject]@{ Name = 'aName'; Ip = 'anIP'; Status = 'aStatus' }。其他脚本:$a = .\Common.ps1; $a.Name; $a.Ip; $a.Status.
    • 是的,这就是我关于封装选项 (a) 的意思,@GeorgesZ。
    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多