Powershell Zip 文件夹内容 [英] Powershell Zip Folder Contents

查看:62
本文介绍了Powershell Zip 文件夹内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道关于使用 Powershell 压缩文件已经有很多介绍,但是我找不到完全符合我需要的方法.

I know a lot has been covered on zipping files using Powershell however I cannot find a method which does exactly what I need.

我希望能够将文件夹和文件压缩到 .zip 文件夹中,而无需将父文件夹放在 zip 中.例如,我有一个名为 STUFF 的文件夹,其中包含文件/文件夹,我想将其压缩到名为 STUFF.zip 的文件夹中.该文件夹结构将是 STUFF.zip>files/folders NOT STUFF.zip>STUFF>files/folders,因为我目前正在使用此代码...

I want to be able to zip folders AND files into a .zip folder without having the parent folder inside the zip. So for example I have a folder named STUFF which contains files/folders, I want to zip this into a folder called STUFF.zip. This folders structure would then be STUFF.zip>files/folders NOT STUFF.zip>STUFF>files/folders as I currently get using this code...

function CountZipItems(
[__ComObject] $zipFile)
{
If ($zipFile -eq $null)
{
    Throw "Value cannot be null: zipFile"
}

Write-Host ("Counting items in zip file (" + $zipFile.Self.Path + ")...")

[int] $count = CountZipItemsRecursive($zipFile)

Write-Host ($count.ToString() + " items in zip file (" `
    + $zipFile.Self.Path + ").")

return $count
}

function CountZipItemsRecursive(
[__ComObject] $parent)
{
If ($parent -eq $null)
{
    Throw "Value cannot be null: parent"
}

[int] $count = 0

$parent.Items() |
    ForEach-Object {
        $count += 1

        If ($_.IsFolder -eq $true)
        {
            $count += CountZipItemsRecursive($_.GetFolder)
        }
    }

return $count
}

function IsFileLocked(
[string] $path)
{
If ([string]::IsNullOrEmpty($path) -eq $true)
{
    Throw "The path must be specified."
}

[bool] $fileExists = Test-Path $path

If ($fileExists -eq $false)
{
    Throw "File does not exist (" + $path + ")"
}

[bool] $isFileLocked = $true

$file = $null

Try
{
    $file = [IO.File]::Open(
        $path,
        [IO.FileMode]::Open,
        [IO.FileAccess]::Read,
        [IO.FileShare]::None)

    $isFileLocked = $false
}
Catch [IO.IOException]
{
    If ($_.Exception.Message.EndsWith(
        "it is being used by another process.") -eq $false)
    {
        Throw $_.Exception
    }
}
Finally
{
    If ($file -ne $null)
    {
        $file.Close()
    }
}

return $isFileLocked
}

function GetWaitInterval(
[int] $waitTime)
{
If ($waitTime -lt 1000)
{
    return 100
}
ElseIf ($waitTime -lt 5000)
{
    return 1000
}
Else
{
    return 5000
}
}

function WaitForZipOperationToFinish(
[__ComObject] $zipFile,
[int] $expectedNumberOfItemsInZipFile)
{
If ($zipFile -eq $null)
{
    Throw "Value cannot be null: zipFile"
}
ElseIf ($expectedNumberOfItemsInZipFile -lt 1)
{
    Throw "The expected number of items in the zip file must be specified."
}

Write-Host -NoNewLine "Waiting for zip operation to finish..."
Start-Sleep -Milliseconds 1000 # ensure zip operation had time to start

[int] $waitTime = 0
[int] $maxWaitTime = 60 * 1000 # [milliseconds]
while($waitTime -lt $maxWaitTime)
{
    [int] $waitInterval = GetWaitInterval($waitTime)

    Write-Host -NoNewLine "."
    Start-Sleep -Milliseconds $waitInterval
    $waitTime += $waitInterval

    Write-Debug ("Wait time: " + $waitTime / 1000 + " seconds")

    [bool] $isFileLocked = IsFileLocked($zipFile.Self.Path)

    If ($isFileLocked -eq $true)
    {
        Write-Debug "Zip file is locked by another process."
        Continue
    }
    Else
    {
        Break
    }
}

Write-Host                           

If ($waitTime -ge $maxWaitTime)
{
    Throw "Timeout exceeded waiting for zip operation"
}

[int] $count = CountZipItems($zipFile)

If ($count -eq $expectedNumberOfItemsInZipFile)
{
    Write-Debug "The zip operation completed succesfully."
}
ElseIf ($count -eq 0)
{
    Throw ("Zip file is empty. This can occur if the operation is" `
        + " cancelled by the user.")
}
ElseIf ($count -gt $expectedCount)
{
    Throw "Zip file contains more than the expected number of items."
}
}

function ZipFolder(
[IO.DirectoryInfo] $directory)
{
If ($directory -eq $null)
{
    Throw "Value cannot be null: directory"
}

Write-Host ("Creating zip file for folder (" + $directory.FullName + ")...")

[IO.DirectoryInfo] $parentDir = $directory.Parent

[string] $zipFileName

If ($parentDir.FullName.EndsWith("\") -eq $true)
{
    # e.g. $parentDir = "C:\"
    $zipFileName = $parentDir.FullName + $directory.Name + ".zip"
}
Else
{
    $zipFileName = $parentDir.FullName + "\" + $directory.Name + ".zip"
    #$zipFileName = $directory.Name + ".zip"
    #$zipFileName = $parentDir.FullName + ".zip"
}

If (Test-Path $zipFileName)
{
    Throw "Zip file already exists ($zipFileName)."
}

Set-Content $zipFileName ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))

$shellApp = New-Object -ComObject Shell.Application
$zipFile = $shellApp.NameSpace($zipFileName)

If ($zipFile -eq $null)
{
    Throw "Failed to get zip file object."
}

[int] $expectedCount = (Get-ChildItem $directory -Force -Recurse).Count
$expectedCount += 1 # account for the top-level folder

$zipFile.CopyHere($directory.FullName)
#Get-ChildItem $directory | foreach {$zipFile.CopyHere($_.fullname)}

# wait for CopyHere operation to complete
WaitForZipOperationToFinish $zipFile $expectedCount

Write-Host -Fore Green ("Successfully created zip file for folder (" `
    + $directory.FullName + ").")
}

用法

Remove-Item "H:\STUFF.zip"

[IO.DirectoryInfo] $directory = Get-Item "H:\STUFF"
ZipFolder $directory

完全归功于 此处用于此代码.我非常感谢我得到的任何帮助,此功能对我的项目至关重要!不幸的是,我无法使用社区扩展模块,因为将在其上运行的其他 PC 没有安装此模块.

Complete credit goes here for this code. I really appreciate any help I get, this capability is crucial to my project! Unfortunately I cannot use the Community Extension module as other PC's this will be run on does not have this module installed.

谢谢!

推荐答案

根据@mjolinor "H:\Stuff\",如果您安装了 .NET 4.5,您可以运行以下命令:

As per @mjolinor "H:\Stuff\", if you have .NET 4.5 installed you can run the following:

$src = "H:\Stuff\"
$dst = "H:\Stuff.zip"
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
[System.IO.Compression.ZipFile]::CreateFromDirectory($src, $dst)

这篇关于Powershell Zip 文件夹内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆