1

stuck at this one trying to store function output in a variable:

function AD-prompt($Text)
{
do
{
$in = read-host -prompt "$Text"
}
while($in -eq "")
}

calling the function with

$type = AD-prompt "Sample Text"

does not store anything in $type - only when i remove the entire do-while loop it works. it seems the function output is empty as the read-host output is stored in the $in variable, but i have no idea how to solve this - i didnt find another way to loop the read-host aswell sadly.

1 Answer 1

4

You need to return $in from your function by outputting it. You can do this by putting it on a line on its own after your loop:

function AD-prompt($Text)
{
    do
    {
       $in = read-host -prompt "$Text"
    }
    while($in -eq "")

    $in
}
Sign up to request clarification or add additional context in comments.

5 Comments

You have to do this, OP, because your Function AD-Prompt didn't actually return anything. You were storing output in the $in variable, but not outputting that back. Due to variable scoping, the value of the variable goes away when the function exits.
Doesn't $in also stop existing outside of the loop? @FoxDeploy
Just a point of improvement, I'd use the Do { ... } Until ($in) construct
i thought it was such a simple mistake - thanks, i guess when i dont store the read-host output in a variable it turns the output into the function output?
Yes anything not output explicitly to anything else (such as a variable or as input to another function/cmdlet) will get returned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.