Reputation: 139
I am trying to to create an efficient PowerShell script that moves a list of files of .xlsx extension into another folder. About 30 files get generated with the current month and year at the end e.g "- January 2018" into this folder path \otnas6uk\sd.test-it.com$\PROJECTS\
Ideally if the Month and Year could be defined at the start so it loops through all files in the root directory and moves them to the correct folder listed.
This is pseudocode of how I think it could work.
$month = "February" $year = "2018"
Move-Item -Path "\\otnas6uk\sd.test-it.com$\PROJECTS\\Zentic Report - $month $year.xlsx" -Destination \\zemnas\sd.Zentic-test.com$\Technology\Reports
All files and destinations would be predefined with only the month and year used as a parameter.
Upvotes: 0
Views: 5179
Reputation: 506
May be this should help move forward:
$Month = "Febuary";
$Year = "2018"
dir .\excelfiles\*$Month*$Year.xlsx|%{move-item -Path $_.FullName -Destination .\Destination.Folder}
Upvotes: 0
Reputation: 101
$oldFolder = '\\otnas6uk\sd.test-it.com$\PROJECTS\\Zentic Report'
$jan2018Folder = '\otnas6uk\sd.test-it.com$\PROJECTS'
# Get a list of the files ending with .xlsx
$files = Get-ChildItem $oldFolder | Where { $_.Extension -eq '.xlsx' }
# Move each file over to the new directory
foreach ($file in $files) {
# Repeat if for all months
if ($file.Name -like '*January*' -and $file.Name -like '*2018*') {
$newPath = "$jan2018Folder\$($file.Name)"
}
Move-Item $file $newPath
}
Upvotes: 1
Reputation: 17171
#region inputs
$month = 12
$year = 2018
$sourceDirectory = "C:\temp"
$destinationDirectory = "C:\destination"
$fileFilter = "*.xlsx"
#endregion
#region input validation
if (-not (Test-Path -Path $sourceDirectory)) {
throw "Can't find source directory"
}
# Month has to be between 1 and 12
if ($month -lt 1 -or
$month -gt 12
) {
throw "BAD MONTH!"
}
# Recent-ish years only
if ($year -lt ((Get-Date).Year - 1) -or
$year -gt ((Get-Date).Year + 2)
) {
throw "BAD YEAR!"
}
#region
#region destination
# Build up new folder path
$destinationDirectory = Join-Path -Path $destinationDirectory -ChildPath $year
$destinationDirectory = Join-Path -Path $destinationDirectory -ChildPath $month
#Create destination if not exists
if (-not (Test-Path -Path $destinationDirectory)) {
New-Item -Path $destinationDirectory -ItemType Directory | Out-Null
}
#endregion
#region move files
Get-childItem -Path $sourceDirectory -File -Filter $fileFilter |
Move-Item -Destination $destinationDirectory
#engregion
Upvotes: 1