Passing and returning a variable

Welcome Forums General PowerShell Q&A Passing and returning a variable

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

4 years, 8 months ago.

  • Author
  • #15971

    Points: 0
    Rank: Member

    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){

    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?

  • #15972

    Points: 0
    Rank: Member

    Typically, you would do it like this:

    Function Get-Input ($Message){
        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.
    $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

    Points: 0
    Rank: Member

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

The topic ‘Passing and returning a variable’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort