none
getting user input from a nested function RRS feed

  • Question

  • Hello There,

    I want to create a nested function that will do some processing and based on that processing it may need user input to continue. However, when I try running my code, it gets weird output.

    Set-Variable -Name setme -Option AllScope
    $setme = "not set"
    $nestedfunction = {
        Write-Output "inside the function `n"
        $setme = Read-Host "Enter Something"
        Write-Output "inside the function setme is: $setme `n"
    }
    
    Write-Output "Outisde call: $(&$nestedfunction)"
    Write-Output "outside it is $setme"

    Then when I run it I get:

    Enter Something: abc
    Outisde call: inside the function 
     inside the function setme is: abc 
    
    outside it is not set

    Regardless of how I nest the function it still ends up like this

    Set-Variable -Name setme -Option AllScope
    $setme = "not set"
    
    $parentfunction = {
        Write-Output "In parent `n"
        $childfunction = {
    
            Write-Output "inside the function `n"
            $setme = Read-Host "Enter Something"
            Write-Output "inside the function setme is: $setme `n"
        }
        Write-Output "Calling child function `n"
        &$childfunction
    }
    
    Write-Output "Outisde call: $(&$parentfunction)"
    Write-Output "outside it is $setme"
    
    Enter Something: abc
    Outisde call: In parent 
     Calling child function 
     inside the function 
     inside the function setme is: abc 
    
    outside it is not set

    The end goal is to be able to call a child function, have it process some data, and if the data is invalid, ask the user to re-enter the data. In my actual script that I want to have this set in, it wont even acknoweldge the Read-Host calls but instead will just bypass them executing everything else. Does anyone know what I am missing?

    Many Thanks Everyone!

    Saturday, June 30, 2018 12:01 AM

Answers

  • $setme  cannot be changed from inside any function as it is defined in an outer scope.  "Visibility" does not mean "writeability".  TO change a variable in an outer scope we must use the scope identifier to reference the variable.


    \_(ツ)_/

    • Marked as answer by MuckingFedic Sunday, July 1, 2018 2:53 PM
    Saturday, June 30, 2018 12:05 AM

All replies

  • $setme  cannot be changed from inside any function as it is defined in an outer scope.  "Visibility" does not mean "writeability".  TO change a variable in an outer scope we must use the scope identifier to reference the variable.


    \_(ツ)_/

    • Marked as answer by MuckingFedic Sunday, July 1, 2018 2:53 PM
    Saturday, June 30, 2018 12:05 AM
  • Ah ok.  I see what I am doing wrong.  I am not at the advanced level of powershell yet so I have yet to learn the scope identifiers but I will read up on them in the about docs.  Thank you :)
    Sunday, July 1, 2018 2:53 PM