[英]How to invoke a function from within a powershell script?
How do I print a list of files by invoking Get-FilesByDate
from within the files.ps1
script itself? 如何通过从
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/")
Additionally, or alternately, populate an array with the file names? 另外,还是可以用文件名填充数组? Any and all files, or
txt
. 任何和所有文件,或
txt
。
Write-Output
is rarely needed, because you can rely on PowerShell's implicit output behavior : 很少需要
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/"
Note how the arguments must be passed without parentheses around the argument list and separated by whitespace , not with the pseudo method syntax you've attempted. 请注意, 参数必须如何在参数列表周围不加括号并通过空格分隔而不是尝试使用的伪方法语法进行传递 。
In other words: PowerShell commands (cmdlets, function, scripts, aliases) are invoked like shell commands , not like methods in C#. 换句话说: PowerShell命令(cmdlet,函数,脚本,别名)的调用类似于shell命令 ,而不是C#中的方法。
In order to pass the output from a command as an argument to another command: 为了将命令的输出作为参数传递给另一个命令:
(...)
or (...)
或 @(...)
or @(...)
或 $(...)
(or @(...)
) $(...)
(或@(...)
)中 Thus, in order to use Write-Output
explicitly (which, as stated, isn't necessary), you'd have to write: 因此,为了显式使用
Write-Output
(如上所述,这不是必需的),您必须编写:
Write-Output (Get-FilesByDate "txt" 1 1 "/home/thufir/")
To populate an array with the output from Get-FilesByDate
: 要用
Get-FilesByDate
的输出填充数组 :
$files = @(Get-FilesByDate "txt" 1 1 "/home/thufir/")
The @(...)
ensures that $files
receives an array even if the function happens to return only a single file; 在
@(...)
确保$files
接收,即使函数发生只返回一个文件数组; alternatively, you could type-constrain the variable and thereby ensure that it is an array: 或者,您可以对变量进行类型约束 ,从而确保它是一个数组:
[array] $files = Get-FilesByDate "txt" 1 1 "/home/thufir/"
Note, however, that explicit use of arrays is often not necessary in PowerShell (since version 3), because even scalars (single values) implicitly act like arrays - see this answer . 但是请注意,在PowerShell(从版本3开始)中, 通常不需要显式使用数组 ,因为即使标量(单个值)也隐式地充当数组 ,请参见答案 。
Further reading: 进一步阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.