在powershell中调用函数,然后如果函数再次调用自身,如何重置函数的变量

问题描述 投票:0回答:1

我的函数进行测试,如果真的再次调用函数

但在这种情况下,我的变量$ label不为空。

我需要重置它,不知道该怎么做

我以为$ label =“”可以工作,但它没有重置它。

我的代码

Function name-label
{

# Incorporate Visual Basic into script
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

    # show the Pop Up with the following text.
    $label = [Microsoft.VisualBasic.Interaction]::InputBox("Pas plus de 11 caractères`r`n`
    1) Que des lettres ou des chifres`
    2) Pas de caractères bizarres comme $ * µ %"`
    , "Nom de la clef USB", "")


    # si plus de 11 caractères
    if ($label.length -gt 12)
        {
            Write-Host "Vous avez mis plus de 11 caractères : $label" -ForegroundColor Red -BackgroundColor Black
            $a = new-object -comobject wscript.shell
            $intAnswer = $a.popup("Vous avez tapé ce nom $label qui est trop long pour la clé USB`r `n Pas plus de 11 caractères`r `n Nouvel essai !",0,"ERREUR !",0)
            name-label # Restart function
        }
}
function powershell reset
1个回答
0
投票

递归调用Name-Label是完全没必要的,你可以用一个简单的do{}until()循环来做到这一点:

Function Name-Label
{    
    # Import Visual Basic into script
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

    $firstRun = $true

    # show the Pop Up with the following text.
    do{
      if(-not $firstRun){
        # loop running again, must have failed input validation
        $null = (New-Object -ComObject WScript.Shell).Popup("Vous avez tapé ce nom $label qui est trop long pour la clé USB`r `n Pas plus de 11 caractères`r `n Nouvel essai !",0,"ERREUR !",0)
      }
      $firstRun = $false

      # prompt user for label
      $label = [Microsoft.VisualBasic.Interaction]::InputBox("Pas plus de 11 caractères`r`n`
      1) Que des lettres ou des chifres`
      2) Pas de caractères bizarres comme $ * µ %",
      "Nom de la clef USB", "")

    } until ($label -match '^[\d\p{L}]{1,11}$')

    return $label
}

用于输入验证的正则表达式模式如下:

^[\d\p{L}]{1,11}$

^         # start of string
 [        
  \d      # digits
  \p{L}   # Letters
 ]        
 {1,11}   # between 1 and 11 of the previous character class
$         # end of string
© www.soinside.com 2019 - 2024. All rights reserved.