locked
Problem passing variable values to Function in PowerShell RRS feed

  • Question

  • New to PowerShell and having a newbie type problem.
    I have a veriable that is initialized in the start of the script to a value of zero, later in the script the value is updated based on conditions met in another function, When i pass the variable to the next function the value is set to null and thelogic in the function does not work.

    Example:
    # Initialization Section of the script includes
    $wordtest = 0
    $CG = 0

    One of the functions in the script set the value of $wordtest based on meeting certian conditions, then the value of $CG is set using

     if($wordtest -gt 0)
    {
     $CG = $CG + 1
    }

    The Display-Logic function start with:

    function Display-Logic {
    Param ($AT, $CG)
    .
    .
    .

    I then pass the AT$ and $CG variables to the Display-Logic function using this line on the script

    Display-Logic $AT, $CG


    When i debug the script I find that the $AT retains it's value ($AT=1) but the $CG loses it's value (#CG= )

    I have tried to use both of thses formats on the first line of the function with the same results
     
    function Display-Logic ($AT, $CG) {
    .
    .
     
    and

    function Display-Logic {
    Param ($AT, $CG)
     .
     .

    Any help will be greatly appreciated

    Thursday, May 26, 2011 5:10 PM

Answers

  • You pass param as array,not single object.

    Display-Logic $AT $CG -remove ,

    • Proposed as answer by s.h.s. _ Friday, May 27, 2011 11:12 AM
    • Marked as answer by AlanRSchroeder Thursday, June 2, 2011 1:08 PM
    Thursday, May 26, 2011 5:16 PM
  • What happens if you change the scope of the $GC variable to script when you declare it? 

    $script:CG = 0



    Andreas Hultgren
    MCTS, MCITP
    http://ahultgren.blogspot.com/
    Thursday, May 26, 2011 8:07 PM

All replies

  • You pass param as array,not single object.

    Display-Logic $AT $CG -remove ,

    • Proposed as answer by s.h.s. _ Friday, May 27, 2011 11:12 AM
    • Marked as answer by AlanRSchroeder Thursday, June 2, 2011 1:08 PM
    Thursday, May 26, 2011 5:16 PM
  • if i'm understanding your problem correctly, you are assigning a value to a variable. but then, you're declaring that same variable name be a parameter for a user-defined function.  if this isn't causing your problem, i'd recommend changing that coding practice up regardless.

    Thursday, May 26, 2011 6:22 PM
  • What happens if you change the scope of the $GC variable to script when you declare it? 

    $script:CG = 0



    Andreas Hultgren
    MCTS, MCITP
    http://ahultgren.blogspot.com/
    Thursday, May 26, 2011 8:07 PM