如何编写代码以基于FileName移动excel文件?

时间:2019-05-02 13:29:58

标签: powershell

我想使用Powershell根据服务器上文件名将excel文件从一个文件夹移动到另一个文件夹。 例如:

\Desktop\SourceTestARC\ to \Desktop\DestinationTestARC\14_file,
\Desktop\SourceTestARC\ to \Desktop\DestinationTestARC\51_file, 
\Desktop\SourceTestARC\ to \Desktop\DestinationTestARC\55_file, etc.

脚本应读取Excel文件的前两位,并将其移至相应的文件夹。

例如:

1420193344.dat goes to 14_file, 
51201997748.dat goes to 51_file.

2 个答案:

答案 0 :(得分:0)

获取源文件夹的Get-Childitems,然后创建一个foreach循环。

将文件名保存在一个变量中,然后使用$ Variable.Substring语句获取必要的两位数字,创建一个变量(例如$ DestinationFolder),在其中将源文件夹与两位数字的变量合并在一起。 然后,使用Copy-Item Cmdlet将文件复制到新的目标位置,对于-destination参数,请使用$ DestinationFolder变量。

答案 1 :(得分:0)

这是一个可能的解决方案:

# Set the Path of the SourceFiles
$SourcePath = "C:\Users\Packard-User\Desktop\Neuer Ordner\"

# get all items of the folder
$FilesInFolder = Get-ChildItem -Path $SourcePath



foreach ($SourceFile in $FilesInFolder)
{

    # i dont like complex statements, because of that a use a helper variable
    $Helper1 = $SourceFile.Name

    # create the destination folder variable, take two characters from the beginning (0), adding the "\" is necessary to show it is a folder
    $DestinationFolder = $SourcePath+$Helper1.Substring(0,2)+"\"

    
    # create the destination folder, throws an exception if the folder already exists
    New-Item -Path $DestinationFolder -ItemType Directory

    # move the item to the destinationfolder
    Copy-Item -Path $SourceFile.FullName -Destination $DestinationFolder
    
    
}