[英]Powershell - Problem with Get-Childitem -include
我正在嘗試編寫一個 PowerShell 腳本,該腳本將允許用戶傳入一個參數,其中包含他們想要處理的多種類型的文件(即 *.txt 和 *.docx)。 當我使用 -include 選項運行 Get-Childitem 命令並手動輸入文件類型時,它可以正常工作 file. 但是當我嘗試為 -include 掩碼提供變量時,它不起作用(不返回任何內容)。
只有當我使用多種文件類型時才會出現問題 $incFiles = “”” .txt””`, “” .docx”””
如果我使用單一文件類型,它工作得很好。 $incFiles = “*.txt”
$incFiles = ""
$incFiles = """*.txt""`, ""*.docx"""
Write-Host "Manual Method:" '"*.txt", "*.docx"'
Write-Host "Calcul Method:" $incFiles
Write-Host "`nManual method works"
Get-ChildItem -path "C:\users\paul\Downloads" -Recurse -Include "*.txt", "*.docx"
Write-Host "This does not work"
Get-ChildItem -path "C:\users\paul\Downloads" -Recurse -Include $incFiles
Write-Host "End"
結果
Manual Method: "*.txt", "*.docx"
Calcul Method: "*.txt", "*.docx"
Manual method works
Directory: C:\users\paul\Downloads\Test2
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 3/28/2020 9:54 AM 0 File1.txt
-a---- 3/28/2020 9:55 AM 0 File2.docx
This does not work
End
Theo和mclayton在對這個問題的評論中提供了關鍵的指示:
$incFiles = """*.txt""`, ""*.docx"""
創建一個string ,其逐字內容最終為"*.txt", "*.docx"
。
順便說一句:反引號( `
),PowerShell的轉義字符,是沒有必要的,因為,
沒有特殊的意義內"..."
(一個可擴展字符串)。
雖然這看起來像一個數組文字,因為您將它直接傳遞給接受字符串值數組的參數(例如-Include
在這種情況下),但您傳遞的是單個 string ,它被解釋為單個通配符模式,因此將不起作用。
您嘗試執行的操作需要 PowerShell 解析作為PowerShell 源代碼傳遞的字符串的內容- 即,需要額外的評估回合 - 它(幸運的是)不會這樣做。 [1]
與其他 shell 不同,PowerShell 能夠將任何類型的值作為直接參數傳遞給命令,無論是通過變量( $incFiles
,在您的情況下)還是通過表達式/嵌套命令,使用(...)
; 例如, Write-Host -Foreground Yellow ('-' * 10)
)
因此,將您的$incFiles
變量構造為字符串數組,並將該數組按原樣傳遞給-Include
參數:
# Create a string array of wildcard expressions.
# (an [object[]] instance whose elements are of type [string]).
# Note the use of '...' rather than "...", which clearly signals that
# the enclosed text should be taken *verbatim* (rather than being subject to
# *expansion* (string interpolation).
$incFiles = '*.txt', '*.docx'
# Pass the array as-is to -Include
Get-ChildItem -path "C:\users\paul\Downloads" -Recurse -Include $incFiles
有關 PowerShell 如何解析傳遞給命令的不帶引號的參數的全面概述,請參閱此答案。
[1] 相比之下,類似 POSIX 的 shell(例如bash
確實通過所謂的shell 擴展在有限的范圍內對未加引號的變量引用應用額外的評估 - 請參閱此答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.