我们目前正在开发一个脚本,它会压缩某个文件,通过API将其上传到Web服务器,然后再次在本地删除。
这是我们目前的代码:
$sourceFile = "D:\myfile.txt"
$destinationFile = "D:\myfile.zip"
function Add-Zip
{
Param([string]$zipfilename)
if (-not (Test-Path($zipfilename)))
{
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = New-Object -Com Shell.Application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach ($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Start-Sleep -Milliseconds 500
}
}
dir $sourceFile | Add-Zip $destinationFile
Write-Host "zip created"
# code to upload the zip here
Remove-Item $destinationFile
Write-Host "zip removed"
它完美地创建了拉链,上传也有效,但是当尝试使用Remove-Item
删除zip文件时,我们得到了
删除项目:无法删除项目D:\ myfile.zip:进程无法访问文件' D:\ myfile.zip'因为它正被另一个进程使用。
我们如何摆脱这种锁定?我们可以.Dispose()
之后能够删除文件吗?
答案 0 :(得分:0)
好的,在这里找到另一种方式:https://danvers72.wordpress.com/2014/11/18/creating-a-zip-file-from-a-single-file/
这是我的工作代码:
$sourceFile = "D:\myfile.txt"
$destinationFile = "D:\myfile.zip"
<#
.Synopsis
Creates a new archive from a file
.DESCRIPTION
Creates a new archive with the contents from a file. This function relies on the
.NET Framework 4.5. On windwows Server 2012 R2 Core you can install it with
Install-WindowsFeature Net-Framework-45-Core
.EXAMPLE
New-ArchiveFromFile -Source c:\test\test.txt -Destination c:\test.zip
#>
function New-ArchiveFromFile
{
[CmdletBinding()]
[OutputType([int])]
Param
(
# Param1 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
Position=0)]
[string]
$Source,
# Param2 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
Position=1)]
[string]
$Destination
)
Begin
{
[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
}
Process
{
try
{
Write-Verbose "Creating archive $Destination…."
$zipEntry = "$Source" | Split-Path -Leaf
$zipFile = [System.IO.Compression.ZipFile]::Open($Destination, 'Update')
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipfile,$Source,$zipEntry,$compressionLevel)
Write-Verbose "Created archive $destination."
}
catch [System.IO.DirectoryNotFoundException]
{
Write-Host "ERROR: The source $source does not exist!" -ForegroundColor Red
}
catch [System.IO.IOException]
{
Write-Host "ERROR: The file $Source is in use or $destination already exists!" -ForegroundColor Red
}
catch [System.UnauthorizedAccessException]
{
Write-Host "ERROR: You are not authorized to access the source or destination" -ForegroundColor Red
}
}
End
{
$zipFile.Dispose()
}
}
New-ArchiveFromFile -Source $sourceFile -Destination $destinationFile
# code to upload the zip here
Remove-Item $destinationFile