移动项目以更正目的地

时间:2018-05-03 15:00:58

标签: powershell windows-scripting

剧本:

  1. 根据脚本根目录中的文件名创建文件夹列表,每个文件夹按“年/月/日”分解名称
  2. 将每个文件移动到指定的文件夹
  3. 错误消息:

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

    我的问题

    文件不会移动到正确的endpath

    #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 个答案:

答案 0 :(得分:0)

把它想出来!只需要将$ file更改为$ f。感谢您的帮助。

答案 1 :(得分:0)

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

  1. MD命令的尾随-confirm您必须回答
  2. Move-Item有一个-WhatIf,显示没有参数
  3. 的情况

    如果脚本正常,请将它们全部删除。

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