2

I am trying to create powershell script function to zip a folder excluding some folders and files here is my code, which create zip file including all files and folder

# Zip creator method

function create-zip([String] $aDirectory, [String] $aZipfile){
    [string]$pathToZipExe = "C:\Program Files\7-zip\7z.exe";
    [Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory";
    & $pathToZipExe $arguments;
}

but i want to exclude *.tmp files and bin and obj folder

I found Get-ChildItem "C:\path\to\folder to zip" -Recurse -Exclude *.txt, *.pdf | %{7za.exe a -mx3 "C:\path\to\newZip.zip" $_.FullName} is working fine as powershell command but how to use it in function of script file

Plz suggest...

user1619672
  • 259
  • 1
  • 7
  • 15

1 Answers1

1

If that one-liner works then putting it in a function is pretty straight forward:

function Create-Zip([string]$directory, [string]$zipFile, [string[]]$exclude=@())
{
    $pathToZipExe = "C:\Program Files\7-zip\7z.exe"
    Get-ChildItem $directory -Recurse -Exclude $exclude | 
        Foreach {& $pathToZipExe a -mx3 $zipFile $_.FullName}
}

If you need to exclude directories then change the Get-ChildItem line to:

    Get-ChildItem $directory -Recurse -Exclude $exclude | Where {!$_.PSIsContainer} |
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Quick one - Where do you place these functions actually so that powershell can have access to them – pal4life Jun 08 '17 at 21:18
  • 1
    You can put the function above in your profile.ps1 script (located under $home\Documents\WIndowsPowerShell). PowerShell will process that script whenever it loads and that function will be available. – Keith Hill Jun 12 '17 at 21:54