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

mac*_*ack 9 powershell function

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

Do-Stuff $aSingleFolder

Do-Stuff $anArrayofFolders
Run Code Online (Sandbox Code Playgroud)

Nic*_*ick 9

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

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
Run Code Online (Sandbox Code Playgroud)

然后当你调用函数时.像这样做

$Folders | Do-Stuff
Run Code Online (Sandbox Code Playgroud)

这将是将要发生的事情.Begin块中的所有内容都将首先运行.然后,对于$Folders变量中的每个项目,Process块中的所有内容都将运行.完成后,它将运行End块中的内容.这样,您可以根据需要将多个文件夹传输到函数中.如果您想在某天向此功能添加其他参数,这非常有用.

  • 请注意,正如使用`[String] $ Folders`声明的那样,此函数将_only_用于通过管道传递的多个值.如果你将参数声明更改为`[string []] $ Folders`,那么你可以在`process`块中`foreach($ f in $ Folders)`,它将适用于`Do-Stuff <one folder> ,`Do-Stuff <multiple>,<folders>`和`<multiple>,<folders> | DO-Stuff`.(哦,反引号是不必要的:开括号和括号数作为延续:) (3认同)

Lee*_*Lee 7

在Powershell中,您可以以统一的方式迭代数组和单个元素:

function Do-Stuff($folders) {
    foreach($f in $folders) {
        //do something with $f
    }
}
Run Code Online (Sandbox Code Playgroud)

传递单个元素将导致foreach与给定项目一起执行一次.

Do-Stuff "folder"
Do-Stuff "folder1", "folder2",...
Run Code Online (Sandbox Code Playgroud)