繁体   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