Search code examples
powershellloopsforeachcompress-archive

PowerShell - Double loop possible?


I want to compress a directory in a specific place. The source path is : \\$Computers\Users\$Names

I want than for each computers a copy of each users directory in the sources path of each computers

I tried to use a foreach loop like :

$Computers = Get-ADComputer -Filter "Name -like 'PC*'" | Select-Object -ExpandProperty Name
$Names = Get-aduser -filter * | Select-Object -ExpandProperty givenname 

Foreach($Computer in $Computers)
{
    Compress-Archive -Path \\$Computer\Users\* -DestinationPath C:\Saves\\$Computer\Test.zip -Force
}

This actually work, but I don't know how can I add a second loop inside the loop.

If anyone can just explain me the function or just some advises please for trying to do that.

Thank you for your time.


Solution

  • You're approaching the problem with the wrong logic, you do need an inner loop, however, instead of attempting to compress a user profile that you don't know for sure is there you can instead query the remote computer's Users folder to see which ones are there and compress only those ones:

    $Computers = (Get-ADComputer -Filter "Name -like 'PC*'").Name
    # Add the profiles you want to exclude here:
    $toExclude = 'Administrator', 'Public'
    $params = @{
        Force = $true
        CompressionLevel = 'Optimal'
    }
    
    foreach($Computer in $Computers)
    {
        $source = "\\$Computer\Users"
        Get-ChildItem $source -Exclude $toExclude -Directory | ForEach-Object {
            $params.LiteralPath = $_.FullName
            # Name of the zipped file would be "ComputerExample - UserExample.zip"
            $params.DestinationPath = "C:\Saves\$computer - {0}.zip" -f $_.Name
            Compress-Archive @params
        }
    }