Powershell 如何在创建zip文件后删除该文件?文件一直在使用中

Powershell 如何在创建zip文件后删除该文件?文件一直在使用中,powershell,zip,Powershell,Zip,我们目前正在编写一个脚本,该脚本压缩某个文件,通过API将其上载到web服务器,然后再次在本地删除该文件 这是我们当前的代码: $sourceFile = "D:\myfile.txt" $destinationFile = "D:\myfile.zip" function Add-Zip { Param([string]$zipfilename) if (-not (Test-Path($zipfilename))) { Set-Cont

我们目前正在编写一个脚本,该脚本压缩某个文件,通过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"
它完美地创建了zip文件,上传也可以,但是当尝试使用
删除项
删除zip文件时,我们得到

删除项:无法删除项D:\myfile.zip:进程无法访问文件“D:\myfile.zip”,因为另一个进程正在使用该文件


我们怎样才能摆脱这把锁?有什么方法可以
.Dispose()
在以后删除该文件吗?

好的,在这里找到另一种方法:

这是我的工作代码:

$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
$sourceFile=“D:\myfile.txt”
$destinationFile=“D:\myfile.zip”
函数newarchivefromfile
{
[CmdletBinding()]
[输出类型([int])]
Param
(
#参数1帮助说明
[参数(必需=$true,
ValueFromPipelineByPropertyName=$false,
位置=0)]
[字符串]
$Source,
#参数2帮助说明
[参数(必需=$true,
ValueFromPipelineByPropertyName=$false,
职位=1)]
[字符串]
$Destination
)
开始
{
[System.Reflection.Assembly]::LoadWithPartialName(“System.IO.Compression.FileSystem”)| Out Null
}
过程
{
尝试
{
写详细的“创建存档$Destination…”
$zipEntry=“$Source”|分割路径-叶
$zipFile=[System.IO.Compression.zipFile]::打开($Destination,'Update'))
$compressionLevel=[System.IO.Compression.compressionLevel]::最佳
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipfile,$Source,$zipEntry,$compressionLevel)
写详细的“已创建存档$destination”
}
catch[System.IO.DirectoryNotFoundException]
{
写入主机“错误:源$source不存在!”-ForegroundColor红色
}
catch[System.IO.IOException]
{
写入主机“错误:文件$Source正在使用或$destination已存在!”-ForegroundColor红色
}
捕获[系统.未授权的访问异常]
{
写入主机“错误:您无权访问源或目标”-ForegroundColor红色
}
}
终点
{
$zipFile.Dispose()
}
}
新建ArchiveFromFile-源$sourceFile-目标$destinationFile
#在这里上传zip的代码
删除项目$destinationFile

ShellApplication对象可能保留了该文件,您可能只需要将
删除变量-Force-Name ShellApplication
添加到
添加Zip
函数的末尾来清理该文件。
foreach($file in$input)
-什么是$input?我无法复制它,
Shell.Application
似乎没有锁定文件。试着使用Process Explorer检查它是否有句柄(可能是AV?)这里提到“通过API上传到Web服务器”,但没有相关代码,因此这也可能是一个调查的途径。代码与我使用的完全相同,包括那里的注释;-)目前没有上传逻辑。这只是以后的一个位置。遗憾的是,Remove Variable-Force-Name$shellApplication也以错误告终。“找不到名为'System.\u ComObject'的变量。”