如何在powershell中更新变量中的变量?

时间:2012-08-21 14:01:23

标签: powershell

我正在制作一个脚本的菜单系统,我可以通过使用菜单或将它们作为参数传递给脚本来更改我需要的值。我目前遇到的烦恼之一是在菜单刷新后输入新值后,菜单文本中的变量不会更新为新值。

      $global:drive="C:"

      $title = "Setup 

      "
           $message = "The default variables are:
            VARIABLES TO CHANGE

            1. The Drive Location: $global:drive <<<--- This is the variable that does not update after I change it when I run the script.
       "

      $one = New-Object System.Management.Automation.Host.ChoiceDescription "&1 Drive", "The Drive Location:"

      $options = [System.Management.Automation.Host.ChoiceDescription[]]($one)

     :OuterLoop do 
{ 
    for ($i = 1; )
    {

      $result =  $host.ui.PromptForChoice($title, $message, $options, 1) 

    switch ($result)
        {
            0 {$global:drive = Read-Host "Drive is $global:drive .Set the  Drive Location";
                "The Drive is now: $global:drive";
                break;}

          }

                }
}

 while ($y -ne 100)

最初我没有将变量设置为全局,但在此处阅读可能会有所帮助。它没有,但它也没有受伤。我也试过把它设置为脚本。变量确实发生了变化,因此这比任何东西都更具美感。

由于

1 个答案:

答案 0 :(得分:1)

我运行了你的代码,但我在菜单中进行了更改。我唯一做的就是评论你的第一个$global:drive="C:"。如果这始终位于脚本的顶部,则$global:drive将始终显示C:

您可以使用以下代码检查变量是否存在,然后分配该值(如果该值尚不存在):

if $(!(Get-Variable -Name Drive -Scope global -ErrorAction SilentlyContinue)) { $global:drive="C:" }

如果全局变量Drive存在,它将不执行任何操作。如果它不存在,$global:drive将设置为C:。希望这会有所帮助。

@Norm评论后编辑:

您的邮件未更新的原因是因为$title设置在循环之外。由于$Title已经定义,因此无需在每次循环运行时进行更改。只需在行$Title之前的循环内移动$result = $host.ui.PromptForChoice($title, $message, $options, 1)的声明即可。这应该可以解决您遇到的问题。

Edit2:对不起,需要移动的是$message,而不是$title