将字符串或字符串数组传递给Powershell中的函数
我希望这是一个简单的问题。我有一个Powershell功能,可以对给定文件夹中的所有文件进行操作。有些时候,我想让这个功能在一个文件夹上运行,并且我希望它能够在多个文件夹上运行,这些文件夹的路径存储在一个数组中。有没有办法让一个函数能够接受单个元素和一个数组?将字符串或字符串数组传递给Powershell中的函数
Do-Stuff $aSingleFolder
Do-Stuff $anArrayofFolders
您也可以在函数中运行流程部分。它看起来像这样:
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
然后当你调用函数。像这样做
$Folders | Do-Stuff
以下是会发生的事情。 Begin
块中的所有内容都将首先运行。然后,对于$Folders
变量中的每个项目,Process
块中的所有内容都将运行。完成后,它将运行End
区块中的内容。这样,您可以根据需要将多个文件夹放入您的功能中。如果您想在某一天为此功能添加其他参数,这非常有用。
在Powershell的,可以遍历以均匀的方式的阵列,并且单个元件:
function Do-Stuff($folders) {
foreach($f in $folders) {
//do something with $f
}
}
传递单个元件将导致与给定的项目执行一次在foreach。
Do-Stuff "folder"
Do-Stuff "folder1", "folder2",...
好,我觉得很愚蠢。 :)那太容易了!我所做的是将函数声明从Do-Stuff([string] $文件夹)更改为Do-Stuff($文件夹),它似乎正在工作。我已经尝试了foreach循环,但是我得到一个错误:“......给定路径的格式不被支持”,因为“给定路径”是来自数组的多个值。我现在调用这样的函数: Do-Stuff $文件夹 Do-Stuff $ folderArray 为什么在声明函数参数时不必包含[string]? – mack 2012-08-08 19:59:01
此作品,未经CMD.EXE和使用文件:
function Invoke-PlinkCommandsIOS {
param (
[Parameter(Mandatory=$true)][string] $Host,
[Parameter(Mandatory=$true)][System.Management.Automation.PSCredential] $Credential,
[Parameter(Mandatory=$true)][string] $Commands,
[Switch] $ConnectOnceToAcceptHostKey = $false
)
$PlinkPath="$PSScriptRoot\plink.exe"
$commands | & "$PSScriptRoot\plink.exe" -ssh -2 -l $Credential.GetNetworkCredential().username -pw "$($Credential.GetNetworkCredential().password)" $Host -batch
}
用法:不要忘记你的退出的和终端长度为0,否则将挂
PS C:\> $Command = "terminal lenght 0
>> show running-config
>> exit
>> "
>>
PS C:\> Invoke-PlinkCommandsIOS -Host ace-dc1 -Credential $cred -Commands $Command
....
太棒了。谢谢Nick。 – mack 2012-08-20 18:02:34
没问题,我绝对喜欢做这样的功能,即使它们很小。重写功能在更大规模上工作的时间有几个小时。祝您有个愉快的一周! – Nick 2012-08-20 22:48:15
请注意,正如使用'[String] $ Folders'声明的那样,此函数将仅适用于通过管道传递的多个值。如果将参数声明更改为'[string []] $ Folders',那么您可以''在'process'块中foreach($ f文件夹中的$ f),它可以用于'Do-Stuff','Do -Stuff ,',和', | DO-Stuff'。 (哦,反引号是不必要的:开括号和括号计数作为延续:) –
2012-09-09 21:48:40