copy files from one location to another in powershell script, in addition checking for certain values

36,921

If there are no subfolders in testfiles(at least that you need files from), try this:

$src = "C:\Users\ainfowara\Desktop\testfiles"
$dst = "C:\Users\ainfowara\Desktop\destinationTestfiles"

Get-ChildItem $src -Filter "txt.*.test.*" | Move-Item -Destination $dst -Force

If you have files in subfolders of the source-path, try this:

$src = "C:\Users\ainfowara\Desktop\testfiles"
$dst = "C:\Users\ainfowara\Desktop\destinationTestfiles"

Get-ChildItem $src -Filter "txt.*.test.*" -Recurse | % {
    #Creates an empty file at the destination to make sure that subfolders exists
    New-Item -Path $_.FullName.Replace($src,$dst) -ItemType File -Force
    Move-Item -Path $_.FullName -Destination $_.FullName.Replace($src,$dst) -Force
}

Be aware that if your filename contains square-bracket [ ] you need another script (known PS bug).

Share:
36,921
ainFowara
Author by

ainFowara

Updated on July 09, 2022

Comments

  • ainFowara
    ainFowara almost 2 years

    So I have folder with files in it, in a certain location

    C:\Users\ainfowara\Desktop\testfiles
    

    so I want to move those files to this location

    C:\Users\ainfowara\Desktop\destinationTestfiles
    

    the "testfiles" have files of this format txt.*.test.* so basically I wanna check before I move the files that they have those two main stuff (txt) and (test) in the third part.

    can someone help me, how can perform this in powershell script

    I know I can do this, to set the folders paths

    path_src= C:\Users\ainfowara\Desktop\testfiles
    path_dst= C:\Users\ainfowara\Desktop\destinationTestfiles
    

    thanks in advance for the help

    • Frode F.
      Frode F. about 11 years
      ".. ... in the third part." what's the third part? Are you saying the the FILENAMES are txt.(something).test.(something)? Or is the content inside that's like this? If it's the filenames: is the last (something) the extension or is it txt.(something).test.(something).extension?
    • ainFowara
      ainFowara about 11 years
      txt.(something).test.(something).extension it could end up with anything, after second something it could be date then extension format, there no specific thing
  • Kris Coleman
    Kris Coleman over 6 years
    this gave me errors, it created empty files for the subfolders but never changed them to folders and copied over the folder contents. this worked instead: $sourceRoot = "C:\temp" $destinationRoot = "C:\n" Copy-Item -Path $sourceRoot -Filter "*.txt" -Recurse -Destination $destinationRoot -Container