Search code examples
functionpowershellreset

calling a function in powershell then how to reset a function's variable if function calls again itself


My function make a test and if it's true calls again the function

But in this case my variable $label isn't empty.

I need to reset it and don't know how to do that

I was thinking that $label="" can works but it doesn't reset it.

here my code

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

Solution

  • Recursively calling Name-Label is completely unnecessary, you can do this with a simple do{}until() loop:

    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
    }
    

    The regex pattern used for input validation is as follows:

    ^[\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