【问题标题】:Cannot find an overload with ForEach loop找不到 ForEach 循环的重载
【发布时间】:2015-12-11 13:47:30
【问题描述】:

这是我的 powershell 代码:

$SourceZipFolder = "C:\temp\TEST\tempzip"

New-Item -type directory -path $SourceZipFolder

[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null

$CompressionLevel= [System.IO.Compression.CompressionLevel]::Optimal

$FileSource = Get-ChildItem -Path "C:\temp\TEST" | Where-Object LastWriteTime -lt (get-date).AddDays(-2)


Move-Item $FileSource.FullName -Destination $SourceZipFolder

Foreach ($Fichiers in $FileSource) {
$ZipDestination ="C:\temp\TEST\archive\$($Fichiers.Name).zip"
[io.compression.zipfile]::CreateFromDirectory($SourceZipFolder, $ZipDestination, $CompressionLevel)
}

Remove-Item -Path $SourceZipFolder -Recurse

我在执行时遇到了这个错误:

Cannot find an overload for "CreateFromDirectory" and the argument count: "3".
At C:\Users\test\Desktop\temp.ps1:17 char:1
+ [io.compression.zipfile]::CreateFromDirectory($SourceZipFolder, $ZipDestination, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

我的ForEach 循环不接受[io.compression.zipfile]::CreateFromDirectory 中的$CompressionLevel 参数,我不明白为什么...因为当我使用For 循环而不是ForEach 时,它可以工作...

感谢您的帮助

我使用 Powershell V4。

【问题讨论】:

  • A 没有看到带有三个参数的 CreateFromDirectory 的任何重载。
  • CreateFromDirectory 有三个参数的重载,但方法签名是 CreateFromDirectory(String, String, Encoding)。但是,您正在尝试将 CompressionLevel 作为编码传递给它。

标签: .net powershell foreach


【解决方案1】:

如果你想设置一个压缩级别并且不关心编码类型那么你需要使用下面的方法签名:

CreateFromDirectory(String, String, CompressionLevel, Boolean)

https://msdn.microsoft.com/en-us/library/hh485721%28v=vs.110%29.aspx

对于代码的相关部分:

Foreach ($Fichiers in $FileSource) {
    $ZipDestination ="C:\temp\TEST\archive\$($Fichiers.Name).zip"
    [io.compression.zipfile]::CreateFromDirectory($SourceZipFolder, $ZipDestination, $CompressionLevel, $false)
}

注意最后的附加参数。如果您希望基本源目录包含在 zip 文件中,则需要使用 $true;如果您只想将源目录的内容包含在 zip 文件中,则需要使用 $false。

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 2015-03-27
    • 2011-06-13
    • 1970-01-01
    • 2020-02-19
    • 2017-07-13
    • 2018-02-28
    • 2021-05-28
    相关资源
    最近更新 更多