Issue incrementing from inside a function

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 11 months ago.

  • Author
    Posts
  • #5765

    by kittH at 2013-04-04 12:34:38

    Hello, I'm having a strange issue.

    I have a script we use to create new users and among other things, it is supposed to assign them a phone number.

    The nuts and bolts of the user creation are all contained in a function "New-User"

    The script accepts a bunch of mandatory parameters, and can be run interactively, or accepting input from a CSV file where it calls the function foreach row in the CSV.

    In the beginning of a script I say:
    $ILPhoneIncrement = 0
    $FLPhoneIncrement = 0

    I also have some logic that generates two arrays of potential phone numbers, $ILNumbers and $FLNumbers

    Later on, inside the New-User function I have the following code:

    #Pick a phone number
    Do
    {
    If($Location -eq 'IL')
    {
    $phoneNumber = "{0:###-###-####}" -f [int64]$ILNumbers[$ILPhoneIncrement]
    $extension = $phoneNumber.Substring(8,4)
    $Global:ILPhoneIncrement++
    "Trying phone number $phoneNumber - increment $ILPhoneIncrement"
    }
    If($Location -eq 'FL')
    {
    $phoneNumber = "{0:###-###-####}" -f [int64]$FLNumbers[$FLPhoneIncrement]
    $extension = $phoneNumber.Substring(8,4)
    $Global:FLPhoneIncrement++
    "Trying phone number $phoneNumber - increment $FLPhoneIncrement"
    }
    }
    Until(!(Get-QADUser -PhoneNumber $phoneNumber))
    "Phone number $phoneNumber chosen" | Add-Content $Log

    If I execute the script with debugging in ISE, everything works fine.
    If I just execute this code ad-hoc in a powershell window, everything works fine.
    When I execute my script by right-click "Run with powershell" it will never increment the variables, it just endlessly loops on the first item in the array with the increment at 0.

    Any ideas what might be happening? Is there a better way to accomplish this?

    by mjolinor at 2013-04-04 13:20:12

    Not sure if this will solve your problem or not, but..

    Using global variables is generally bad practice. You can avoid that (and having to explicitly scope those variables inside the functions) if you us a hash table instead of variables.

    Create a hash table in your main script:
    $PhoneIncrement = @{FL=0;IL=0}

    Then inside your function you can do this
    $PhoneIncrement.FL++
    $PhoneIncrement.IL++

    Instead of having to use (and scope) global variables.

    by kittH at 2013-04-04 13:43:37

    I can't test that right now, but that's exactly the type of thing I was looking for. I should be able to test tomorrow.

    Thanks Mjolinor.

You must be logged in to reply to this topic.