Move a folder to archive along with specific files

Tagged: 

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of venkatesh SQL venkatesh SQL 3 months, 2 weeks ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #42184
    Profile photo of venkatesh SQL
    venkatesh SQL
    Participant

    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

    foldera
    folderb
    folderc
    folderd
    foldere
    Archive

    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
    Profile photo of random commandline
    random commandline
    Participant

    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.
    https://mcpmag.com/articles/2014/09/29/file-frontier-part-6.aspx

    $source = "C:\Temp\"
    $dest = "C:\Temp\Archive"
    $files = Get-ChildItem -Path $source -Recurse -Exclude Archive -Include '*.txt','*.csv','*.xls'
    Add-Type -assembly 'system.io.compression.filesystem'
    
    foreach ($file in $files){
    $folder = $file.directoryname | Split-Path -Leaf
    
    # Create zip
    If (!(Test-Path $dest$folder.zip)){New-Item $dest$folder.zip -ItemType file}
    
    # Add files to zip
    $zip = [io.compression.zipfile]::Open("$dest$folder.zip",'Update')
    [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$file.FullName,$file.name)
    $zip.dispose()
    }
    
    # Results
    # Archive\foldera.zip    
    # Archive\folderb.zip
    
    #42517
    Profile photo of venkatesh SQL
    venkatesh SQL
    Participant

    Thanks very much.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.