Home > Software engineering >  Copy certain files from folder - and give each file a date-stamp
Copy certain files from folder - and give each file a date-stamp

Time:04-28

I have a script that look for specific filenames, and copy those to another destination. No problem here, what I need help with is to give each file a _date/time in the destinationfolder

Like the copied file file1 get the name file1_20220427

The script I have now is like below:

$search_folder = "H:\SOURCE"
$destination_folder = "H:\DEST"
$file_list =  @("file1","file2")
foreach ($file in $file_list) 
{
$file_to_move = Get-ChildItem -Path $search_folder  | % { $_.FullName}
if ($file_to_move) 
{
    Copy-Item $file_to_move $destination_folder
}
}

CodePudding user response:

Without modifying too much of your code, there isn't a need for a foreach loop as you can pipe directly to Copy-Item:

$search_folder      = "H:\SOURCE\*"
$destination_folder = "H:\DEST\"
$file_list          =  "file1*","file2*"
Get-ChildItem -Path $search_folder -Include $file_list -File|
    Copy-Item -Destination { 
        $destination_folder    ($_.BaseName   "_"   (Get-Date).ToString("yyyyMMdd")   $_.Extension)  
    } 

This is doable since Copy-Item can accept a scriptblock where you can modify the destination path to include a concatenated result. All that's needed is to provide the destination path, the basename property to keep the beginning of the name, append the date in format of yyyMMdd, and the extension to keep the file type.

Also, take note of the use of -Include. This parameter can accept an array of names to search for where you would need to provide the full name (extension included), or part of it with a wildcard (asterisk -*) allowing us to get rid of the foreach statement.

  • The only issue when using -Include is that it's PowerShell's solution to providing a search filter and not a file system provider based one.
  • Therefore, the source path has to include an asterisk at the end of the folder path, or the use of -Recurse is needed.

Now, your file names should reflect file1_20220427,file2_20220427 and so on accordingly, in your destination folder.

  • Related