PowerShell有效地将项目移动到文件夹

时间:2018-01-17 12:38:53

标签: powershell

我正在尝试创建一个高效的PowerShell脚本,将.xlsx扩展名的文件列表移动到另一个文件夹中。大约30个文件在当前月份和年末生成,例如“ - 2018年1月”到此文件夹路径\ otnas6uk \ sd.test-it.com $ \ PROJECTS \

理想情况下,如果可以在开始时定义月份和年份,那么它会遍历根目录中的所有文件并将它们移动到列出的正确文件夹中。

这是我认为它可以工作的伪代码。

$ month =“二月” $ year =“2018”

GetTxCount

所有文件和目的地都是预定义的,只有月份和年份用作参数。

3 个答案:

答案 0 :(得分:1)

$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
}

答案 1 :(得分:1)

#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

答案 2 :(得分:0)

这可能有助于前进:

$Month = "Febuary";

$Year = "2018"

dir .\excelfiles\*$Month*$Year.xlsx|%{move-item -Path $_.FullName -Destination .\Destination.Folder}