移动项目到正确的目的地

Move-Item to correct Destination

脚本:

  1. 根据脚本根目录中的文件名创建文件夹列表,每个文件夹按 "Year/Month/Day"
  2. 细分名称
  3. 将每个文件移动到指定的文件夹

错误信息:

 CategoryInfo : ObjectNotFound: 
(S:\Data\TECHNOL...59_20180108.txt:String) 
[Move-Item], ItemNotFoundException FullyQualifiedErrorId : 
PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand 

我的问题

文件不会移动到正确的结束路径

#Create Directory
Set-StrictMode -Version 2
$rootPath = split-path -parent $MyInvocation.MyCommand.Definition
cd $rootPath
$FileNameArray = Get-ChildItem -Filter "*.txt"
$FileNameArray = $FileNameArray -replace "....$"
$FileNameArray = $FileNameArray -replace "^59_"

Foreach($f in $FileNameArray)
{
        $Year = $f -replace "^\d{0}|\d{4}$" #"....$"
        $Month = $f -replace "^\d{4}|\d{2}$"
        $Month = $Month | sort -Unique
        $Day = $f -replace "^\d{6}|\d{0}$"
        #Loop 2a
        Foreach($m1 in $Month){
        #Loop 2a-a
            Foreach($d1 in $Day){
                Move-Item -Path ($rootPath + '_' + $file + '.txt') 
-Destination ($rootPath + '\' + $Year + '\' + $m1 + '\' + $d1)
                }
        }
}

对于意大利面条代码和简单的问题表示歉意,我是计算机科学和 PowerShell 的新手。

想通了伙计们!只需要将 $file 更改为 $f。感谢大家的帮助。

以下脚本具有两个安全功能:

  1. MD 命令有尾部 -confirm 你必须回答
  2. Move-Item 有一个 -WhatIf,它显示了没有参数
  3. 时会发生什么

如果脚本运行正常,将它们都删除。


## Q:\Test18\SO_50158185.ps1
Set-StrictMode -Version 2
$rootPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
cd $rootPath

Get-ChildItem "59_20[0-9][0-9][0-1][0-9][0-3][0-9].txt" |
  Where-Object {$_.BaseName -Match '59_(?<year>\d{4})(?<Month>\d{2})(?<Day>\d{2})'}|
    ForEach-Object {
      $DestDir = Join-Path $rootPath ("{0}\{1}\{2}" -f $Matches.Year,$Matches.Month,$Matches.Day)
      If (!(Test-Path $DestDir)) {MD $DestDir -Confirm| Out-Null}
      $_ | Move-Item -Destination $DestDir -WhatIf
    }