Passing and returning a variable

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Tony Wainwright Tony Wainwright 2 years, 6 months ago.

  • Author
    Posts
  • #15971
    Profile photo of Tony Wainwright
    Tony Wainwright
    Participant

    Hi
    Back again. I use a few Read-Host statements in my scripts which all follow a standard and thought it would be simple to create a function (save a few lines of code). This my script:Function Get-Input ($Result, $Message){
    Clear-Host

    Write-Host $Message -ForegroundColor Yellow
    $Result = Read-Host

    }
    $Att = $null
    $Msg = "
    nIf you want to include read-only (r), system (s) or hidden (h) filesn"
    $Msg = $Msg +"type them here separated by comma's. DO NOT include any spaces.`n"
    $Msg = $Msg + "Press ENTER to add no attributes'"

    Get-Input -Result $Att -Message $Msg
    If ($Att -eq "") {$Att = $null}
    Get-ChildItem -Attributes $Att -Path C:\Scripts
    Effectively I am asking the user to input what attributes they want to include in the Get-ChildItem statement (along with a prompt message.

    Using Write-Host (as a debug tool) inside the function I can see that $Result changes on user input. How do I get it to pass out of the function back into $Att?
    Thanks
    Tony

  • #15972
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Typically, you would do it like this:

    Function Get-Input ($Message){
        Clear-Host
        Write-Host $Message -ForegroundColor Yellow
        
        # Note that Read-Host's result is not assigned to a variable inside the function.  This
        # allows its result value to be send to the function's Output stream.
    
        Read-Host
    }
    
    $Msg = 'Some User prompt'
    
    # The output from the Get-Input function is assigned to a variable out here, in the script scope.
    $result = Get-Input -Message $Msg
    
  • #15973
    Profile photo of Tony Wainwright
    Tony Wainwright
    Participant

    Ta Dave – I knew that! Wood for the trees and all that.

You must be logged in to reply to this topic.