powershell - 将项目移动到正确的目的地
问题描述
剧本:
- 根据脚本根目录中的文件名创建文件夹列表,每个文件夹按“年/月/日”分解名称
- 将每个文件移动到指定文件夹
错误信息:
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 都是新手。
解决方案
以下脚本具有两个安全功能:
- 该
MD
命令有一个尾随-confirm
你必须回答 - 有
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
}
推荐阅读
- node.js - 如何在nodejs中使用带有sequelize的where子句中的request.body数组
- r - 如何计算时间间隔并将其除以r中的整数?
- wordpress - Wordpress:适合每个地区的网站?另一个更好的CMS?
- php - 包含在 php 变量中
- python - Sqlalchemy + pymssql 连接失败
- angularjs - 在 AngilarJS 中使用获取请求时出错
- android - 使用相机时 onActivityResult resultCode 始终为 0
- html - 将元素浮动到最大宽度
- php - 如果有分数,php只显示小数位
- regex - 排版检查中的正则表达式