mac*_*ack 9 powershell function
我希望这是一个简单的问题.我有一个Powershell函数,可以对给定文件夹中的所有文件进行操作.有时我希望该功能在单个文件夹上运行,有时候我希望它在几个文件夹上运行,其路径存储在一个数组中.有没有办法让一个函数能够接受单个元素和一个数组?
Do-Stuff $aSingleFolder
Do-Stuff $anArrayofFolders
Run Code Online (Sandbox Code Playgroud)
您还可以在函数中运行流程部分.它看起来像这样:
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块中的内容.这样,您可以根据需要将多个文件夹传输到函数中.如果您想在某天向此功能添加其他参数,这非常有用.
在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)
| 归档时间: |
|
| 查看次数: |
12769 次 |
| 最近记录: |