Move a folder to archive along with specific files

This topic contains 2 replies, has 2 voices, and was last updated by  venkatesh SQL 2 years ago.

  • Author
  • #42184

    venkatesh SQL

    How to write powershell script to archive folders only when the folder has files of certain type for instance (.txt, .csv, .xls, .xlsx). My source path is "C:\Temp\Test\" and there are 5 sub-folders


    Only foldera, folderb, folderc have the files to be archived, the archive path is "C:\Temp\Test\Archive" and this has folders foldera, folderb so these folders need not be created but files need to be zipped and copied, folderc needs to be created and the files have to be zipped and copied.

    Using the code below I get the files but not the folder that particular file was in. I am able to create the folders but get error if the folder already exists and if I just copy-item I can move just the files but cannot create the folder. Please guide me.

    ​$source = "C:\Temp\"

    $archive = "C:\Temp\Archive"

    $archive = Get-ChildItem -Recurse -Path $source -include *.txt, *.csv, *.xls| select directory | sort -Unique -Property Directory | Select -expand Directory | Copy-Item -Destination $archive

    If (!(Test-Path $archive)) {

    Get-ChildItem -Recurse -Path $source -include *.txt, *.csv, *.xls | select directory | sort -Unique -Property Directory | Select -expand Directory | Copy-Item -Destination $archive


    else {

    Write-Host "Directory $archive already exists!"


  • #42283

    random commandline

    This will display files as they are added to zip files. If you want to learn more about adding to zip files using .NET and PowerShell, check the link.

    $source = "C:\Temp\"
    $dest = "C:\Temp\Archive"
    $files = Get-ChildItem -Path $source -Recurse -Exclude Archive -Include '*.txt','*.csv','*.xls'
    Add-Type -assembly ''
    foreach ($file in $files){
    $folder = $file.directoryname | Split-Path -Leaf
    # Create zip
    If (!(Test-Path $dest${New-Item $dest$ -ItemType file}
    # Add files to zip
    $zip = [io.compression.zipfile]::Open("$dest$",'Update')
    # Results
    # Archive\    
    # Archive\
  • #42517

    venkatesh SQL

    Thanks very much.

You must be logged in to reply to this topic.