-2

Im trying to create a PowerShell script that moves a list of files into another folder, depending on the file name. One example of the file name 'Test-AMM - Report'.

Original Location

\\oltnas6uk\sd.test.com$\PROJECTS\Account Management\Test-AMM - Report

File Destination

\\ammnasuk\rd.test-amm.com$\Business Management\Regular\Reporting

The bold highlights the keyboards that I can use to determine which location the file will go into.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
dcraven
  • 139
  • 4
  • 16

1 Answers1

0

It's pretty straightforward to do this.

Start with getting a list of the files you're looking to move into an array called $files:

$files=get-childitem "\\oltnas6uk\sd.test.com$\PROJECTS\Account Management\"

Then you use a foreach loop to iterate through the array, and use a switch in regular expressions mode to match patterns on the file and determine what to do:

foreach ($f in $files) {
    switch -regex ($f.Name) {
        "AMM" {
            try {
                Move-Item -Path $f.FullName -Destination "\\ammnasuk\rd.test-amm.com$\Business Management\Regular\Reporting" -Force
            } catch {
                Write-Host "Couldn't move file ($f.Name), error was $($_.Exception.Message)" -foregroundcolor red
            }
            break;
        }
        "BMM" {
            try {
                Move-Item -Path $f.FullName -Destination "\\bmmnasuk\rd.test-amm.com$\Business Management\Regular\Reporting" -Force
            } catch {
                Write-Host "Couldn't move file ($f.Name), error was $($_.Exception.Message)" -foregroundcolor red
            }
            break;
        }
    }
}

}

I would suggest that you either add logging to your script or spend enough time making sure that your pattern matches won't generate unexpected results. If there are a lot of files in the destination, it's also worth running a comparison against all your expected matches to see how many files don't match any of your rules.