powershell - 压缩存档错误 : PermissionDenied

标签 powershell

我正在尝试使用 Powershell v5.1 压缩文件夹,但某些文件已被另一个进程使用,PS 无法强制或忽略它们。

Get-ChildItem "C:\folder" | Compress-Archive -DestinationPath "C:\file.zip"

还用 -Force-ErrorAction Ignore,Continue,SilentlyContinue 进行了测试,但每次我都会遇到这样的错误:

ZipArchiveHelper : The process cannot access the file 'C:\folder\filexyz' be cause it is being used by another process.
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:69
6 char:30
+ ... sArchived = ZipArchiveHelper $subDirFiles.ToArray() $destinationPath  ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\folder\filexyz:String) [Write-Error], IOException
    + FullyQualifiedErrorId : CompressArchiveUnauthorizedAccessError,ZipArchiveHelper

New-Object : Exception calling ".ctor" with "1" argument(s): "Stream was not readable."
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:80
7 char:38
+ ...     $srcStream = New-Object System.IO.BinaryReader $currentFileStream
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

最佳答案

异常:使用“1”参数调用“.ctor”的异常:“流不可读。” 当使用多个文件与 Compress-Archive 并且一个或多个打开时发生.

您可以在将文件传送到 Compress-Archive 之前检查文件是否未锁定。

$items = Get-ChildItem -Path $path
[System.Collections.ArrayList]$itemsToCompress = @()
[System.Collections.ArrayList]$itemsToNotCompress = @()

foreach ($item in $items){
    Try {
        # Checking File Mode and Access
        $FileStream = [System.IO.File]::Open($item.FullName,'Open','Read')
        if ($null -ne $FileStream){
            $FileStream.Close()
            $FileStream.Dispose()
            $itemsToCompress += $item
        }
    }
    Catch {
        $itemsToNotCompress += $item
    }
}

$itemsToCompress | Compress-Archive -DestinationPath $archivefile -ErrorAction SilentlyContinue

关于powershell - 压缩存档错误 : PermissionDenied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48684948/

相关文章:

powershell - 在PowerShell中将字符串安全地转换为bool

powershell - 内联函数调用,其中需要表达式

excel - Powershell等待Excel中执行宏

python - 相当于 Unix "shell function"的 Powershell 脚本

regex - 在PowerShell中获取所有指定的子字符串

c# - 如何处理自定义 Powershell Cmdlet 的依赖项

powershell - 使用 Powershell 从文件中获取父目录和修改日期

powershell - 使用 RemotedSigned 时信任哪些文件夹

json - PowerShell - JSON/PsCustomObject - 为什么我的数组会被展平为单个对象?

search - PowerShell FINDSTR 等效吗?