簡體   English   中英

使用包含開關的變量時,Get-ChildItem失敗

[英]Get-ChildItem Fails When Using a Variable With the Include Switch

Powershell v4.0 Windows 7

此代碼工作並檢索我正在嘗試查找的2個文件:

$dir = Get-Item -Path "C:\TestSource"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include *.txt,*.inf

此代碼也有效,但它只找到txt文件:

$Dir = Get-Item -Path "C:\TestSource"
$Filter = "*.txt"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

但是,這不會返回任何對象:

$Dir = Get-Item -Path "C:\TestSource"
$Filter = "*.txt,*.inf"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

有必要將$ Filter變量構建到一個數組中,如下所示:

$Dir = Get-Item -Path "C:\TestSource"
$Filter = @("*.txt","*.inf")
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

Get-ChildItem上的Microsoft頁面讓我相信可以將變量與Get-ChildItem cmdlet一起使用。 但是,除非變量是數組,否則為什么cmdlet不返回對象? 由於顯式字符串在第一個示例中起作用,第三個示例是否也應該起作用?

Include的參數總是一個數組 - 在你的第一個例子中-Include *.txt,*.inf傳遞一個雙元素數組作為過濾器。

在第三個示例中,它是逗號分隔的字符串。 如果你傳遞一個數組它應該工作:

$Dir = Get-Item -Path "C:\TestSource"
$Filter = "*.txt", "*.inf"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

李給出了答案; 在第三個示例中,您嘗試為-Include參數傳遞多個值以進行求值,但是您沒有將其作為數組進行適當格式化,因此腳本正在查找名稱中包含整個字符串模式的文件: *.txt,*.inf

暫無
暫無

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

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