如何在 PowerShell 复制脚本中正确过滤多个字符串

2023-12-10

我正在使用来自的 PowerShell 脚本这个答案进行文件复制。当我想使用过滤器包含多种文件类型时,就会出现问题。

Get-ChildItem $originalPath -filter "*.htm"  | `
   foreach{ $targetFile = $htmPath + $_.FullName.SubString($originalPath.Length); ` 
 New-Item -ItemType File -Path $targetFile -Force;  `
 Copy-Item $_.FullName -destination $targetFile }

就像做梦一样。但是,当我想使用过滤器包含多种文件类型时,就会出现问题。

Get-ChildItem $originalPath ` 
  -filter "*.gif","*.jpg","*.xls*","*.doc*","*.pdf*","*.wav*",".ppt*")  | `
   foreach{ $targetFile = $htmPath + $_.FullName.SubString($originalPath.Length); ` 
 New-Item -ItemType File -Path $targetFile -Force;  `
 Copy-Item $_.FullName -destination $targetFile }

给我以下错误:

Get-ChildItem : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Filter'. Specified method is not supported.
At F:\data\foo\CGM.ps1:121 char:36
+ Get-ChildItem $originalPath -filter <<<<  "*.gif","*.jpg","*.xls*","*.doc*","*.pdf*","*.wav*",".ppt*" | `
    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.GetChildItemCommand

我有括号的各种迭代,没有括号,-filter, -include,将包含物定义为变量(例如,$fileFilter)并且每次都会出现上述错误,并且总是指向后面的内容-filter.

有趣的例外是当我编码时-filter "*.gif,*.jpg,*.xls*,*.doc*,*.pdf*,*.wav*,*.ppt*"。没有错误,但我没有得到任何结果,也没有返回到控制台。我怀疑我无意中编码了一个隐含的代码and与该声明?

那么我做错了什么,我该如何纠正呢?


-Filter只接受单个字符串。-Include接受多个值,但限定-Path争论。技巧是附加\*到路径的末尾,然后使用-Include选择多个扩展名。顺便说一句,在 cmdlet 参数中不需要引用字符串,除非它们包含空格或 shell 特殊字符。

Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*

请注意,无论是否$originalPath以反斜杠结尾,因为多个连续的反斜杠被解释为单个路径分隔符。例如,尝试:

Get-ChildItem C:\\\\\Windows
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 PowerShell 复制脚本中正确过滤多个字符串 的相关文章

随机推荐