Windows 使用包含开关的变量时,Get ChildItem失败

Windows 使用包含开关的变量时,Get ChildItem失败,windows,variables,powershell,Windows,Variables,Powershell,Powershell v4.0 视窗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 "$($di

Powershell v4.0 视窗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

上的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

是的,我发现了。。。。。但是我重新修改了我的问题(在你发布之前3分钟)以查找“询问原因”。感谢你更新了答案,这是完全有意义的。此外,Get ChildItem将-Include参数传递给文件系统提供程序,它实际上不处理这些参数本身。当它通过
-Include*.txt时,*.ini
powershell会看到一个由两个字符串组成的数组。当它被告知“.txt,.ini”时,它会看到一个9个字符长的字符串,因此它会将该字符串传递给提供程序,然后提供程序会查找包含字符串
“*.txt,*.ini”
的文件,但它永远找不到该字符串。您可能已经忘记了编辑时间。在我写第一篇评论的时候,他还没有编辑他的答案。