Benn
Benn

Reputation: 45

How to move bunch of files to a daily create folder

I'm creating a script to do the following tasks:

  1. Find all zip files based on current date
  2. Extract the zip files to a Temporary folder
  3. Rename all the extract's files extension from dat to txt
  4. Move all renamed .txt files from the Temporary folder to a daily create folder

Please see my code:

$input = "U:\PS\Input"
$TempZip = "U:\PS\ExtractedZip"
$dest = "U:\PS\Output"
$filelist = Get-ChildItem $input -Filter "*.Zip" -Recurse |
            Where-Object{$_.LastWriteTime -eq (Get-Date).AddDays(1)}
$shell_app = New-Object -Com Shell.Application
foreach ($file in $filelist) {
    $zip_file = $shell_app.NameSpace($file.FullName)           
    foreach ($item in $zip_file.Items()) {
        $shell_app.NameSpace($TempZip).CopyHere($item)
    }
    Get-ChildItem -Path $TempZip -Filter "*.dat" -Recurse |
        Rename-Item -NewName {[IO.Path]::ChangeExtension($_.Name, "txt")} -PassThru |
        Move-Item -Path "$TempZip\*.txt" -Destination "$dest\MM_YYYY\DD_MM_YYYY\Retail"
}

Note: MM_YYYY: current Month and Year, e.g. August_2017. DD_MM_YYYY: current date, e.g. 23_08_2017.

For example: \August_2017\23_08_2017\Retail

Next day would be: \August_2017\24_08_2017\Retail

I'm stuck at task number 4 and wondering could PowerShell move bunch of files to a daily create folder (a new folder is created everyday in a format \August_2017\23_08_2017\Retail and next day would be \August_2017\24_08_2017\Retail)?

Upvotes: 1

Views: 121

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Build the destination path from the current date using the format operator:

$dest = "U:\PS\Output\{0:MMMM_yyyy}\{0:dd_MM_yyyy}\Retail" -f (Get-Date)

Then move the files like this:

Get-ChildItem -Path $TempZip -Filter "*.dat" -Recurse |
    Move-Item -Destination { Join-Path $dest ($_.BaseName + '.txt') }

You can rename the files while moving, no need to use Rename-Item first.

Upvotes: 1

Related Questions