![](/img/trans.png)
[英]Powershell: How to pass reference of Array from Powershell to C# Function
[英]How to invoke a function from within a powershell script?
如何通过从files.ps1
脚本本身调用Get-FilesByDate
来打印文件列表?
$ pwsh files.ps1
Get-FilesByDate
txt
1
1
/home/thufir/
$ cat files.ps1
Function Get-FilesByDate
{
Param(
[string[]]$fileTypes,
[int]$month,
[int]$year,
[string[]]$path)
Get-ChildItem -Path $path -Include $filetypes -Recurse |
Where-Object {
$_.lastwritetime.month -eq $month -AND $_.lastwritetime.year -eq $year }
} #end function Get-FilesByDate
Write-Output Get-FilesByDate("txt",1,1,"/home/thufir/")
另外,还是可以用文件名填充数组? 任何和所有文件,或txt
。
很少需要Write-Output
,因为您可以依靠PowerShell的隐式输出行为 :
# By neither redirecting nor piping nor capturing the output from
# this call, what it returns is *implicitly* output.
# Note the absence of parentheses and the separation of arguments with whitespace.
Get-FilesByDate "txt" 1 1 "/home/thufir/"
请注意, 参数必须如何在参数列表周围不加括号并通过空格分隔而不是尝试使用的伪方法语法进行传递 。
换句话说: PowerShell命令(cmdlet,函数,脚本,别名)的调用类似于shell命令 ,而不是C#中的方法。
为了将命令的输出作为参数传递给另一个命令:
(...)
或 @(...)
或 $(...)
(或@(...)
)中 因此,为了显式使用Write-Output
(如上所述,这不是必需的),您必须编写:
Write-Output (Get-FilesByDate "txt" 1 1 "/home/thufir/")
要用Get-FilesByDate
的输出填充数组 :
$files = @(Get-FilesByDate "txt" 1 1 "/home/thufir/")
在@(...)
确保$files
接收,即使函数发生只返回一个文件数组; 或者,您可以对变量进行类型约束 ,从而确保它是一个数组:
[array] $files = Get-FilesByDate "txt" 1 1 "/home/thufir/"
但是请注意,在PowerShell(从版本3开始)中, 通常不需要显式使用数组 ,因为即使标量(单个值)也隐式地充当数组 ,请参见答案 。
进一步阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.