locked
Reusing a function RRS feed

  • Question

  • I want to reuse a function, first to browse out to a source folder and then again to browse out to the target folder.  Guess I just don't understand and could use some help.  Here is the script:

    function Find-Folders {
        param ($Folder)
        [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
        [System.Windows.Forms.Application]::EnableVisualStyles()
        $browse = New-Object System.Windows.Forms.FolderBrowserDialog
        $browse.SelectedPath = "C:\"
        $browse.ShowNewFolderButton = $True
        $browse.Description = "Select a " + $Folder + " folder"
    
        $loop = $true
        while($loop)
        {
            if ($browse.ShowDialog() -eq "OK")
            {
            $loop = $false
    		
    		Write-Host "Your source is " $Folder
    		
            } else
            {
                $res = [System.Windows.Forms.MessageBox]::Show("You clicked Cancel. Would you like to try again or exit?", "Select a location", [System.Windows.Forms.MessageBoxButtons]::RetryCancel)
                if($res -eq "Cancel")
                {
                    #Ends script
                    return
                }
            }
        }
        $browse.SelectedPath
        $browse.Dispose()
    }
    
    Find-Folders Source
    
    Find-Folders Target
    

    I need to save the results of the function to a $sourceFolder variable and then to a $targetFolder variable, to reuse in a copy-item command.

    Hope someone can help and thanks in advance.

    Wednesday, July 10, 2019 2:02 PM

Answers

  • You save the output of a function in a variable simply by assigning it to the variable

    $SourceFolderList = Find-Folders Source
    $TargetFolderList = Find-Folders Target
    But you don't reuse the function you will use the output/result of that function.

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    • Edited by BOfH-666 Wednesday, July 10, 2019 2:32 PM
    • Marked as answer by OSPJR Wednesday, July 10, 2019 5:23 PM
    Wednesday, July 10, 2019 2:31 PM

All replies

  • You save the output of a function in a variable simply by assigning it to the variable

    $SourceFolderList = Find-Folders Source
    $TargetFolderList = Find-Folders Target
    But you don't reuse the function you will use the output/result of that function.

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    • Edited by BOfH-666 Wednesday, July 10, 2019 2:32 PM
    • Marked as answer by OSPJR Wednesday, July 10, 2019 5:23 PM
    Wednesday, July 10, 2019 2:31 PM
  • Thank you.  Thought I had tried that.  Copied your two lines and that worked.  Again, thanks.
    Wednesday, July 10, 2019 4:59 PM