Search code examples
powershellloopsforeachcompress-archive

PowerShell Script (foreach-loop problems)


I have a short question, but I am standing on the wall for too long now, so I have to ask you.... The situation is: I have a special filetype, in different folders and subfolders. I already managed to find the files, write them into a TXT-File and I also managed to split the path so I can name a ZIP-File with the Folder-Name and Date. But the only thing I do not get is how to only zip the special file of folder1 in a Zip-archiv "folder1-date.zip" and the file of folder2 in a Zip-archiv "folder2-date.zip". Code part looks like this:

[string[]]$dirs = (Split-Path (Split-Path -Path $output -Parent) -Leaf | Foreach-Object { $i++; $_ })
[string[]]$arrayFromFile = Get-content -Path 'C:\TEMP\output.txt'
foreach ($file in $arrayFromFile) {
foreach ($dir in $dirs){
#
Compress-Archive -Path $file -CompressionLevel Optimal -Update -DestinationPath $destination\$dir-$date.zip }
}

The Problem is, that every file with the extension found is in every ZIP-Archiv (logic because it is a foreach in a foreach) but I can not find the right way to do it.... Thank you for the help!


Solution

  • This will get the desired outcome and not have to save output to a text file.

    $origin = "C:\TEMP\"
    $filetyp = ".stl, .vol, .pct, .tif"
    $destination = "C:\Daten\zipstore\"
    $date = $(Get-Date -Format d)
    
    
    $fileNames = Get-ChildItem "$origin" -Recurse | Where {$_.extension -eq ".stl"} | ForEach-Object { $_.FullName }
    
    foreach ($file in $fileNames) {
    
        $dir = (Split-Path (Split-Path -Path $file -Parent) -Leaf)
        
        Compress-Archive -Path $file -CompressionLevel Optimal -Update -DestinationPath $destination\$dir-$date.zip
    }