将字符串或字符串数​​组传递给Powershell中的函数 [英] Pass string or string array to a function in Powershell

查看:151
本文介绍了将字符串或字符串数​​组传递给Powershell中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这是一个简单的问题。我有一个Powershell功能,可以对给定文件夹中的所有文件进行操作。有些时候,我想让这个功能在一个文件夹上运行,并且我希望它能够在多个文件夹上运行,这些文件夹的路径存储在一个数组中。有没有办法让一个函数可以同时接受单个元素和数组?

  Do-Stuff $ aSingleFolder 

做的东西$ anArrayofFolders


解决方案

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

 函数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.

这篇关于将字符串或字符串数​​组传递给Powershell中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆