Powershell脚本,用于根据源列表移动文件(.txt

时间:2014-04-29 05:35:14

标签: powershell

我在目录(.pdf,.xls,.doc)中有数千个文件,它们都有类似的命名约定(“类型”始终是一个常量字符串,即:开票或发票);

帐户名 _ ACCOUNTNUMBER _type.pdf

accountname _ accountnumber _type.doc

帐户名 _ ACCOUNTNUMBER _type.xls

手头的任务是接收一个随机的帐户名和帐号列表(“类型”始终是一个常数,即:结算,发票,发货或订单,它们的格式各不相同)并将它们从目录A移到目录B.我可以将列表放入.csv文件以匹配 accountname_accountnumber _type。

我一直在尝试创建一个powershell脚本来引用accountname_accountnumber并将这些项目从一个目录A移动到目录B而没有运气。

SAMPLE 我发现了一些更简单的东西,但是我希望能够编辑它来创建一个新目的地,如果没有从该列表中找到该文件,则不会停止。此外,如果我可以从.txt列表中选择此选项,我认为这比粘贴所有内容更容易。

$src_dir = "C:\DirA\"
$dst_dir = "D:\DirB-mm-dd-yyyy\" #This code requires the destination dir to already be there and I need to have the code output a new Directory, it could output based on date script run that would be amazing

$file_list = "accountname1_accountnumber001_type", #If I can select to import csv here
"accountname2_accountnumber002_type",
"accountname3_accountnumber003_type",
"accountname4_accountnumber004_type",
"accountname5_accountnumber005_type",
"accountname6_accountnumber006_type"

foreach ($file in $file_list) #This errors out and stops the script if the file is not located in source and I need to have the script continue and move on, with hopefully an error output
{
  move-Item $src_dir$file $dst_dir
}

它们可以是任何文件格式,我试图让代码只匹配帐户名和帐号,因为这两个将定义确切的客户。无论是发票,账单还是发货都无关紧要,因为他们希望移动与该客户相关的所有文件。

例如,每个帐户可能有4个,类型格式可能会有所不同,pdf,doc和xls,我需要根据前两个指标(accountname,accountnumber)移动所有文件。

alice_001_invoice.pdf

alice_001_billing.doc

alice_001_shipping.pdf

alice_001_order.xls

George_245_invoice.pdf

George_245_billing.doc

George_245_shipping.pdf

George_245_order.xls

Bob_876_invoice.pdf

Bob_876_billing.doc

Bob_876_shipping.pdf

Bob_876_order.xls

Horman_482_invoice.pdf

Horman_482_billing.doc

Horman_482_shipping.pdf

Horman_482_order.xls

CSV:

帐户名,ACCOUNTNUMBER

翘,001

乔治,245

鲍勃,876

Horman,482

2 个答案:

答案 0 :(得分:0)

代码部分 - 您已经从帖子中编辑过 - 关于将文件移动到子目录对您的业务规则没有多大意义。由于您从未显示示例CSV文件内容,因此全部猜测。

为了便于处理,假设您有以下源文件。编辑帖子以显示CSV文件内容以及您要移动文件的位置。

C:\some\path\A\Alice_001_bill.doc
C:\some\path\A\Alice_001_invoice.xls
C:\some\path\A\Bob_002_invoice.pdf
C:\some\path\A\Bob_002_invoice.doc
C:\some\path\A\Eve_003_bill.xls
C:\some\path\A\Eve_003_invoice.doc

答案 1 :(得分:0)

这个怎么样:

$CurrentDate = [DateTime]::Now.ToString("MM-dd-yyyy")
$DestinationDir = "D:\DirB-$CurrentDate"
New-Item $DestinationDir -ItemType Directory -ErrorAction SilentlyContinue

$AccountToMove = Import-CSV $CSVPath
Foreach ( $Account In $AccountToMove ){
    $FilePattern = "*$($Account.AccountName)*$($Account.AccountNumber)*"
    ls $SourceDir | Where Name -like $FilePattern | Move-Item -Destination $DestinationDir
}