2

I have two different ways of getting files with a wildcard pattern:

Get-ChildItem "$ActivityLogDirectory/*.csv"

and

Get-ChildItem "$ActivityLogDirectory" -Filter *.csv

I prefer to use the latter instead of the former because the former (Get-ChildItem "$ActivityLogDirectory/*.csv") has, on occasion, given me a permission denied error.

They both appear to return the same results, but when I try to compress the resulting files with this command:

Compress-Archive -Update -Path $CsvFiles -DestinationPath C:\Users\admin\Downloads\foo.zip

the former succeeds while the latter fails with the following error:

Compress-Archive : The path 'rgb dev automation store a_1-1_2194_20181120.csv'
either does not exist or is not a valid file system path.
At line:1 char:1
+ Compress-Archive -Update -Path $CsvFiles -DestinationPath C:\Users\ad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (rgb dev automat...94_20181120.csv:String) [Compress-Archive], InvalidOperationException
    + FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Compress-Archive

So what's the difference between these two ways of getting a listing of files using wildcards? Or perhaps asked another way, why does using -Filter *.csv cause the Compress-Archive cmdlet to fail?

enter image description here

4

2 回答 2

2

您看到不同行为的原因是 - 模糊的情境 - 对象输出的字符串化行为Get-ChildItem

此答案详细说明了Get-ChildItem输出碰巧字符串化为纯文件名完整路径时的详细信息,并且恰好Get-ChildItem "$ActivityLogDirectory" -Filter *.csv字符串化为纯文件名。

解决方法是通过属性(PSv3+ 语法)将对象显式字符串化为完整路径:FullName

$CsvFiles = (Get-ChildItem "$ActivityLogDirectory" -Filter *.csv).FullName
于 2018-11-29T02:13:07.790 回答
1

如果您从具有 CSV 文件所在文件夹位置的 shell 运行它,那么这将起作用。$CsvFiles通过将变量传递给您正在做的事情Compress-Archive是尝试在当前上下文中针对文件名运行。要解决此问题,请传递完整路径$CsvFiles.FullName

$Csvfiles = (Get-Childitem $ActivityLogDirectory -Filter *.csv)
Compress-Archive -Update -Path $Csvfiles.fullname -DestinationPath C:\Users\admin\Downloads\foo.zip
于 2018-11-28T23:44:05.900 回答