Zip and Unzip File in Powershell 4

后端 未结 5 1672
一生所求
一生所求 2021-02-13 22:14

I am using Windows Server 2012 R2 (64 bit). I have powershell version 4 available in it. I am trying to zip and unzip files. When I try Write-Zip command, it throws me following

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 22:39

    Should work under PS4. SeeAdd-Zip and New-Zipfunctions

    [CmdletBinding()]
    Param(
     [Parameter(Mandatory=$True)]
     [ValidateScript({Test-Path -Path $_ })]
     [string]$sourceDirectory,
    
     [Parameter(Mandatory=$True)]
     [ValidateScript({-not(Test-Path -Path $_ -PathType Leaf)})]
     [string]$destinationFile,
    
     [Parameter(Mandatory=$True)]
     [int]$noOlderThanHours
     ) 
    
     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
          }
     }
    
    $oldest = (Get-Date) - (New-TimeSpan -Hours $noOlderThanHours)
    
    $filesToZip = dir $sourceDirectory -Recurse | Where-Object {$_.lastwritetime -gt $oldest}
    
     Write-Host Going to zip following files 
    
     $filesToZip | foreach {Write-Host $_.FullName}
    
    
    
    $filesToZip| Add-Zip $destinationFile
    

提交回复
热议问题