0
function Compress-CompatibleArchive {
    $contents = Get-Content -Path C:\Users\USER\OneDrive\Documents\WindowsPowerShell\modules\Parameters.txt | Out-Null
    #Split the line into parameter name and value
    $contents -split '='
    $RootPath = $args[1]
    $ClientName = $args[3]
    $SolutionName = $args[5]
    $PluginName = $args[7]
    $DestinationPath = $args[10]
    Write-Host $DestinationPath

    $ZipSourcePath ="$RootPath\$ClientName\CDC.Plugin.$PluginName\bin\$ClientName$PluginName"
    Write-Host $ZipSourcePath
    try {
        # Load .NET assemblies
        Add-Type -AssemblyName 'System.IO.Compression.FileSystem'
        # Normalize paths for cross-platform compatibility
        $sourceDirectory = $ZipSourcePath.TrimEnd([IO.Path]::DirectorySeparatorChar,   [IO.Path]::AltDirectorySeparatorChar)
        $zipFile = [IO.Path]::GetFullPath($DestinationPath)

         # Create a new zip archive
        $zipArchive = [System.IO.Compression.ZipFile]::Open($zipFile, 'Create')

        # Get all files and directories in the source directory and its subdirectories
        $items = Get-ChildItem -Path $ZipSourcePath -Recurse

        # Add each file and directory to the zip archive
        foreach ($item in $items) {
            $relativePath = $item.FullName.Substring($ZipSourcePath.Length + 1)

            if ($item.PSIsContainer) {
                # Directory entry
                $null = $zipArchive.CreateEntry($relativePath + '/')
            } else {
                # File entry
                [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipArchive, $item.FullName, $relativePath, $compressionLevel)
            }
        }

        Write-Host "Successfully created $zipFile"
            }
    catch {
        Write-Error "Failed to create zip file: $_"
    }  
    finally {
        # Close the zip archive
        if ($zipArchive) {
            $zipArchive.Dispose()
       }
    }
}

Question: How can I include the root directory in the zip file using above function?

1 Answer 1

0

All you need is:

  1. Add an extra call to $zipArchive.CreateEntry to create the root directory
  2. Update $relativePath to include the root directory name

To extract the root folder name, use Split-Path:

# ...

# Create a new zip archive
$zipArchive = [System.IO.Compression.ZipFile]::Open($zipFile, 'Create')

# extract root directory name, create root directory entry
$rootDirectoryName = $ZipSourcePath |Split-Path -Leaf 
$zipArchive.CreateEntry($rootDirectoryName) |Out-Null

Then remember to include it when constructing the relative path:

$relativePath = Join-Path $rootDirectoryName $item.FullName.Substring($ZipSourcePath.Length + 1)

Not the answer you're looking for? Browse other questions tagged or ask your own question.