PowerShell不能删除它打开的文件
我在下面写了这段代码。它现在抛出错误
Cannot remove item BLAHBLAH: The process cannot access the file 'BLAHBLAH' because it is being used by another process.
只要整个脚本完成,我就能手动删除该文件。所以我觉得这个脚本在运行时没有正确释放该文件。
是不是有一个 'close file' 命令,或者我忘了什么?
# Get all files in the directory (non-recursive)
$allFiles= Get-ChildItem -Path $sourceDir -File
$files = Get-ChildItem -Path $sourceDir -Filter "*.pdf" -File
if ($allFiles.Count -eq 0) {
Write-Host "No files found in '$sourceDir'."
exit
}
foreach ($file in $files) {
try {
# Create the destination zip path (same folder, same name, .zip extension)
$zipPath = Join-Path $sourceDir ($file.BaseName + ".ZIP")
# Open or Create a zip file stream:
$zipStream = [System.IO.File]::Open($zipPath, 'Create')
# Create a new archive object in the zipStream:
$archive = [System.IO.Compression.ZipArchive]::new($zipStream, 'Create')
# Create a file entry inside the archive from the $twoGBPath name:
$entry = $archive.CreateEntry([System.IO.Path]::GetFileName($file.FullName))
# Open and read data into the $zipStream's $archive $entry:
[System.IO.File]::OpenRead($file.FullName).CopyTo($entry.Open())
# Ensure the file is properly written and valid:
$archive.Dispose()
# Close the zip stream
$zipStream.Dispose()
Write-Host "Zipped '$($file.Name)' to '$zipPath'"
}
catch {
Write-Error "Failed to zip '$($file.Name)': $_"
}
}
#deletes PDF's for which a ZIP was made
$zipped = Get-ChildItem -Path $sourceDir -Filter "*.ZIP" -File
foreach ($zip in $zipped)
{
$deletePath = Join-Path $sourceDir ($zip.BaseName + ".pdf")
Remove-Item -Path $deletePath
}
解决方案
你正在关闭归档流,但没有关闭由 File.OpenRead 返回的 FileStream。我对PowerShell不太熟悉,但我预计解决方案可能是这样的:
替换这个:
[System.IO.File]::OpenRead($file.FullName).CopyTo($entry.Open())
用这个:
$inputStream = [System.IO.File]::OpenRead($file.FullName)
$inputStream.CopyTo($entry.Open())
$inputStream.Dispose()
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。