[英]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.