1

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

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

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

谢谢

4

1 回答 1

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

于 2012-08-21T14:52:02.810 回答