Powershell - 仅压缩文件而不是目录

Powershell - 仅压缩文件而不是目录

我正在使用网站上的脚本关联。但它会压缩目录。我宁愿让它只压缩该目录内的文件,并且压缩文件名应该是 directory.zip。

这是 ZipFolder 函数。有人能告诉我需要做哪些更改才能只压缩目录内的文件吗?

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"
    }

    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)

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

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

#Remove-Item "C:\NotBackedUp\Fabrikam.zip"

[IO.DirectoryInfo] $directory = Get-Item "D:\tmp"
ZipFolder $directory

答案1

首先,欢迎大家的光临。

如果你阅读代码,你会看到文件夹被复制到了 zip 文件中:

$zipFile.CopyHere($directory.FullName)

您需要做的是复制目录中的各个文件。

基本上,您需要进入目录,然后复制每个子项。

cd $Directory.FullName
foreach ($f in (get-childItem .))
{
  $zipFile.CopyHere($f)
}

请注意,您还必须删除:

$expectedCount += 1 # account for the top-level folder

试试看,请注意,我根本没有测试/调试过它,这只是伪代码,我会怎么做。Powershell 很好用,功能强大,但学习难度很高。

答案2

找到了替代方法服务器故障

$srcdir = "H:\Backup"
$zipFilename = "test.zip"
$zipFilepath = "K:\"
$zipFile = "$zipFilepath$zipFilename"

#Prepare zip file
if(-not (test-path($zipFile))) {
    set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
    (dir $zipFile).IsReadOnly = $false  
}

$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipFile)
$files = Get-ChildItem -Path $srcdir | where{! $_.PSIsContainer}

foreach($file in $files) { 
    $zipPackage.CopyHere($file.FullName)
#using this method, sometimes files can be 'skipped'
#this 'while' loop checks each file is added before moving to the next
    while($zipPackage.Items().Item($file.name) -eq $null){
        Start-sleep -seconds 1
    }
}

相关内容