繁体   English   中英

Powershell - Get-Childitem -include 的问题

[英]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

Theomclayton在对这个问题的评论中提供了关键的指示:

$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM