Read-host in function add extra new-line

Welcome Forums General PowerShell Q&A Read-host in function add extra new-line

This topic contains 4 replies, has 4 voices, and was last updated by

 
Participant
3 months, 1 week ago.

  • Author
    Posts
  • #111104

    Participant
    Points: 0
    Rank: Member

    Who can solve this ?

    the code below drives me nuts.  It returns the extra "enter" from the input.

    function myreadhost($question){

    [string]$result

    $result = read-host $question

    return $result

    }

     

    $x = myreadhost "tellme"

     

    $x

    "$x"

    @($x -split "`n").Count

  • #111134

    Participant
    Points: 290
    Helping Hand
    Rank: Contributor

    return $Result.TrimEnd() should sort it out quickly enough. Can't say I've really run into it as an issue as yet, but then I don't really use Read-Host very much 🙂

  • #111280

    Participant
    Points: 878
    Helping Hand
    Rank: Major Contributor

    I do it in below way, If I want to make my parameter as a question with out having mandatory parameter.

    function myreadhost{
    Param(
    $Question,
    [string]$result = $(read-host $question)
    )
    return $result
    }
    

    Making expression as the default value.

  • #111283
    js

    Participant
    Points: 319
    Helping Hand
    Rank: Contributor

    You're returning $result twice in the function. You don't need the return keyword. So it's blank the first time, and then it's set by read-host the second time. Param() is how you declare a variable. Your function can be as simple as:

    function myreadhost($question) {
      read-host $question
    }
  • #111284

    Participant
    Points: 290
    Helping Hand
    Rank: Contributor

    Oh, that's a very good point, js.

    Mirko, worth mentioning a little more succinctly, I think — you're trying to declare a variable at the start of your function. PS doesn't declare variables like you may be used to from some languages like C# or VB.NET

    At the beginning of your function, as js mentions, the value of the variable is $null, because it hasn't been set yet. PowerShell will read that as [string]$null, which is an empty string. This causes an empty string to be added to the output, which is producing the extra blank line, not the keypress from Read-Host.

    If you simply specify a value or a variable on a line with no assignment statement like that, PS's default assumption is that you want to output the value and happily does that. Unlike C# where you must use a return keyword, any value expression left on a line will also be added to the output stream. PS permits functions to return multiple distinct values.

The topic ‘Read-host in function add extra new-line’ is closed to new replies.