Creating zip files in Windows Server Core

In my last post I talked about extracting zip files in Windows Server Core and shared a PowerShell function that I made.

Today I decided to make a new function that you can use to create a new archive. The function uses the same ZipFile class.

<#
.Synopsis
 Creates a new archive from a directory
.DESCRIPTION
 Creates a new archive with the contents from a folder. This function relies on the
 .NET Framework 4.5. On windwows Server 2012 R2 Core you can install it with 
 Install-WindowsFeature Net-Framework-45-Core
.EXAMPLE
 New-ArchiveFromDirectory -SourceDirectory c:\test -Destination c:\test.zip
#>
function New-ArchiveFromDirectory
{
 [CmdletBinding()]
 [OutputType([int])]
 Param
 (
 # Param1 help description
 [Parameter(Mandatory=$true,
 ValueFromPipelineByPropertyName=$false,
 Position=0)]
 [string]
 $SourceDirectory,

 # Param2 help description
 [Parameter(Mandatory=$true,
 ValueFromPipelineByPropertyName=$false,
 Position=1)]
 [string]
 $Destination
 )

 Begin
 {
 [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
 }
 Process
 {
 try
 {
 Write-Verbose "Creating archive $Destination...."
 [System.IO.Compression.ZipFile]::CreateFromDirectory($SourceDirectory, $destination)
 Write-Verbose "Created archive $destination."
 }
 catch [System.IO.DirectoryNotFoundException]
 {
 Write-Host "ERROR: The source directory $SourceDirectory does not exist!" -ForegroundColor Red
 }
 catch [System.IO.IOException]
 {
 Write-Host "ERROR: The destination $destination already exist!" -ForegroundColor Red
 }
 catch [System.UnauthorizedAccessException]
 {
 Write-Host "ERROR: You are not authorized to access the source or destination" -ForegroundColor Red
 }
 finally
 {

 }
 }
 End
 {

 }
}
Advertisements