Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass string or string array to a function in Powershell

I hope this is a simple question. I have a Powershell function that operates on all files in a given folder. There are times when I would like to have the function operate on a single folder and times when I would like it to operate on several folders, the paths of which are stored in an array. Is there a way to have one function be able to accept both a single element and an array?

Do-Stuff $aSingleFolder

Do-Stuff $anArrayofFolders
like image 949
mack Avatar asked Aug 08 '12 18:08

mack


2 Answers

You can also run the process section within the function. It would look like this:

Function Do-Stuff {
    param(
        [Parameter( `
            Mandatory=$True, `
            Valuefrompipeline = $true)]
        [String]$Folders
    )
    begin {
        #Things to do only once, before processing
    } #End Begin

    Process {
         #What  you want to do with each item in $Folders
    } #End Process 

    end {
        #Things to do at the end of the function, after all processes are done
    }#End end
} #End Function Do-Stuff

Then when you call the Function. Do it like this

$Folders | Do-Stuff

Here is what will happen. Everything in the Begin block will run first. Then, for each item in the $Folders variable, everything in the Process block will run. After it completes that, it will run what is in the End block. This way you can pipe as many folders as you want into your function. This is really helpful if you want to add additional parameters to this function some day.

like image 133
Nick Avatar answered Oct 01 '22 17:10

Nick


In Powershell, you can iterate over an array and a single element in a uniform manner:

function Do-Stuff($folders) {
    foreach($f in $folders) {
        //do something with $f
    }
}

Passing a single element will cause the foreach to be executed once with the given item.

Do-Stuff "folder"
Do-Stuff "folder1", "folder2",...
like image 43
Lee Avatar answered Oct 01 '22 18:10

Lee