簡體   English   中英

如何從Powershell腳本中調用函數?

[英]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開始)中, 通常不需要顯式使用數組 ,因為即使標量(單個值)也隱式地充當數組 ,請參見答案


進一步閱讀:

  • PowerShell的解析模式: about_Parsing幫助主題。
  • PowerShell如何解析命令參數:請參見此答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM