I'm trying to compress a folder using Powershell v5.1, but some files are used by another process and PS can't force or ignore them.
Get-ChildItem "C:\folder" | Compress-Archive -DestinationPath "C:\file.zip"
Also tested with -Force and -ErrorAction Ignore,Continue,SilentlyContinue, but every time I get an error like this:
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
The exception: Exception calling ".ctor" with "1" argument(s): "Stream was not readable." occurs when using multiple files with Compress-Archive and one or more are open.
You can check if the files are not locked before piping them to 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With