首页 > 解决方案 > 将项目移动到正确的目的地

问题描述

剧本:

  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 都是新手。

标签: powershellwindows-scripting

解决方案


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

  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
    }

推荐阅读