且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串或字符串数​​组传递给Powershell中的函数

更新时间:2023-11-03 18:24:58

您也可以在函数中运行流程部分。它看起来像这样:

 函数Do-Stuff {
param(
[Parameter(`
必须= $ True,`
Valuefrompipeline = $ true)]
[字符串] $文件夹

begin {
#只能做一次,在处理
之前} #End Begin

处理{
#你想对$ Folders中的每个项目做什么
}#结束处理

end {
#在所有进程完成后,在函数结束时执行的操作
} #End end
} #End函数执行任务

然后当您调用函数时。像这样做

  $文件夹| Do-Stuff 

以下是会发生的情况。 Begin 块中的所有内容都将首先运行。然后,对于 $ Folders 变量中的每个项目, Process 块中的所有内容都将运行。完成后,它将运行 End 块中的内容。这样,您可以根据需要将多个文件夹放入您的功能中。如果你想在某一天添加​​额外的参数,这真的很有用。


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

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.