PowerShell脚本以递归方式压缩许多文件夹中的文件

时间:2017-02-27 16:40:32

标签: powershell recursion zip powershell-v2.0

我想在某个位置递归每个文件夹里面, 例如:C:\ Logs和zip文件到同一个文件夹。

我需要跳过每个.zip文件。我不知道如何让我的脚本执行此操作:

function New-Zip
{
    param([string]$zipfilename)
    set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
    (dir $zipfilename).IsReadOnly = $false
}
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
    }
}
$targetFolder = 'C:\Logs'
$now = Get-Date -Hour 0 -Minute 00 -Second 00
$days = 5
$lastWrite = $now.AddDays(-$days)

Get-ChildItem $targetFolder -Recurse -Exclude *zip* | Where-Object { $_ -is [System.IO.FileInfo] } | ForEach-Object {
    If ($_.LastWriteTime -lt $lastWrite)
    {
        $_ | New-Zip $($targetFolder + $_.Name + ".zip" )
        $_ | Add-Zip $($targetFolder + $_.Name + ".zip" )
    }
}

1 个答案:

答案 0 :(得分:0)

您目前正在排除包含短语' zip'的任何文件或文件夹。在它的名字中,因为你有一个通配符:

Get-ChildItem $targetFolder -Recurse -Exclude *zip*

要排除zip文件,您只需更新Exclude语句,使其仅与zip文件扩展名匹配:

Get-ChildItem $targetFolder -Recurse -Exclude *.zip