如何在Powershell中的脚本之间共享变量?

时间:2018-03-06 03:03:24

标签: powershell variables scripting

我很难找到一个在线解决此问题的答案。

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

$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}

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

1 个答案:

答案 0 :(得分:0)

天真的答案是“点源”这些脚本,即用运算符<?php foreach ($cats as $cat) : if (in_array($cat->getId(), [68, 28, 27, 59, 79, 80, 119])) : $cat_show = Mage::getModel('catalog/category')->load($cat->getId()); $children = $cat_show->getChildrenCategories($cat->getId()); $url1 = $cat_show->getURL(); $showAnyways = in_array(strtolower($cat_show->getName()), ["hats", "juniors", "accessories"]); if ($cat_show->getShowSidebar() == 1 || $showAnyways) : ?> <li class="current<?php if ($cat->getId() == $current_cat) { ?> active <?php } ?>"> <a href="<?php echo $url1 ?>"><?php echo $cat->getName() ?></a> <ul> <?php if ($cat_show->getID() != 68 && $cat_show->getID() != 59) { ?> <li class="current<?php if ($cat->getId() == $current_cat && $j == 0) { $j++; ?> active<?php } ?>"><a class="view_all" href="<?php echo $url1 ?>"><?php echo $this->__("View All"); ?></a></li> <?php } ?> <?php foreach ($children as $subcat) { $subcat_show = Mage::getModel('catalog/category')->load($subcat->getId()); if ($subcat_show->getShowSidebar() == 1 || in_array($subcat_show->getID(), [84])) { $grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId()); if ($grand_children) { $cats_displayed = 0; foreach ($grand_children as $grand_child) { $grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId()); if ($grand_child_show->getShowSidebar() == 1) { $url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL(); ?> <li class="current<?php if ($grand_child->getId() == $current_cat && $j == 0) { $j++; ?> active<?php } ?>"> <a href="<?php echo $url ?>"><?php echo $grand_child_show->getName() ?></a> </li> <?php $cats_displayed++; } } } if ($cats_displayed == 0 || !$grand_children) { $url = Mage::getModel('catalog/category')->load($subcat->getId())->getURL(); ?> <li class="current<?php if ($subcat->getId() == $current_cat && $j == 0) { $j++; ?> active<?php } ?>"> <a href="<?php echo $url ?>"><?php echo $subcat->getName() ?></a> </li> <?php } } } ?> </ul> </li> <?php endif;?> <?php endif;?> <?php endforeach; ?> 调用它们

使用执行调用者的变量范围中的脚本,以便$x的顶级修改即使在{{{}}之后也可见1}}和$z已完成。

.\filename1.ps1

但是,请注意,调用者可以看到在.\filename2.ps1中创建或修改的任何顶级变量 - 调用者。

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

更好的封装选项是(a)输出修改后的值,或者不太常见的是,(b)使用# Note the `. ` preceding the file path - the space after "." is mandatory . .\filename1.ps1 ; "$x text $z text" . .\filename2.ps1 ; "$x text $z text" 参数传递 by-reference变量脚本 - 必须声明其参数并相应地分配。