Creating a zipped/compressed folder in Windows using Powershell or the command line

后端 未结 6 1396
野性不改
野性不改 2020-12-13 04:56

I am creating a nightly database schema file and would like to put all the files created each night, one for each database, into a folder and compress that folder. I have a

6条回答
  •  没有蜡笔的小新
    2020-12-13 05:43

    Here's a couple of zip-related functions that don't rely on extensions: Compress Files with Windows PowerShell.

    The main function that you'd likely be interested in is:

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

    Usage:

    dir c:\demo\files\*.* -Recurse | Add-Zip c:\demo\myzip.zip
    

    There is one caveat: the shell.application object's NameSpace() function fails to open up the zip file for writing if the path isn't absolute. So, if you passed a relative path to Add-Zip, it'll fail with a null error, so the path to the zip file must be absolute.

    Or you could just add a $zipfilename = resolve-path $zipfilename at the beginning of the function.

提交回复
热议问题