代码之家  ›  专栏  ›  技术社区  ›  Dino the Dinosaur

将项目移动到正确的目标

  •  0
  • Dino the Dinosaur  · 技术社区  · 8 年前

    脚本:

    1. 根据脚本根目录中的文件名创建文件夹列表,每个文件夹按“年/月/日”对名称进行细分
    2. 将每个文件移动到指定文件夹

    错误消息:

     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 + '\59_' + $file + '.txt') 
    -Destination ($rootPath + '\' + $Year + '\' + $m1 + '\' + $d1)
                    }
            }
    }
    

    为意大利面代码道歉&简单的问题是,我对计算机科学和PowerShell都是新手。

    2 回复  |  直到 8 年前
        1
  •  0
  •   user6811411 user6811411    8 年前

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

    1. 这个 MD 命令具有尾部 -confirm 你必须回答
    2. 这个 Move-Item 有一个 -WhatIf 它显示了在没有参数的情况下可以执行的操作

    如果脚本工作正常,请同时删除它们。


    ## Q:\Test\2018\05\03\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
        }
    
        2
  •  0
  •   Dino the Dinosaur    8 年前

    伙计们,我明白了!只需将$文件更改为$f。感谢所有帮助。