问题描述
我在一个名为 D:\queries\ 的目录中有数千个如下所示的文件
I have thousands of files like the following in a directory called D:\queries\
#TIM_DV_ORDERINQUERY.SQL
#TIM_QA_ORDERINQUERY.SQL
#TIM_P1_ORDERINQUERY.SQL
#JACK_DV_SALESQUERY.SQL
#JACK_P1_PRODUCTQUERY.SQL
#ERIK_P1_EMPLOYEE-NY.SQL
#ERIK_P1_EMPLOYEE-TX.SQL
::
I am need a script to move them to folders
G:\queries\#TIM\DV\ORDERINQUERY.SQL
G:\queries\#TIM\QA\ORDERINQUERY.SQL
G:\queries\#TIM\P1\ORDERINQUERY.SQL
G:\queries\#JACK\DV\SALESQUERY.SQL
G:\queries\#JACK\P1\PRODUCTQUERY.SQL
G:\queries\#ERIK\P1\EMPLOYEE-NY.SQL
G:\queries\#ERIK\P1\EMPLOYEE-TX.SQL
也就是说第一个 _ 之前的字符是 G:\queries 中的子目录,然后第一个 _ 和第二个 _ 之间的字符是其中的子目录,然后名称的测试是文件名字.
In other words the character before the first _ is the sub directory within G:\queries and then the characters between the first _ and the second _ is the a sub directory within it and then the test of the name is the file name.
我在网上搜索了很多,但我无法弄清楚.我是 powershell 或任何类型的脚本的新手.任何帮助表示赞赏.
I have searched a lot on the web and I can't figure it out. I am new to powershell or any kind of scripting. Any help is appreciated.
推荐答案
这利用了 FileInfo 类,以获取与目录有关的信息.
This makes use of the FileInfo class, to get information pertaining to the directory.
$SourceFolder = "G:\queries\"
$targetFolder = "G:\queries\"
# Find all files matching *.sql in the folder specified
Get-ChildItem -Path $SourceFolder -Filter *.sql | ForEach-Object {
# Combine the source filename and target directory
# The source filename has all instances of _ replaced with \
# Cast the resulting string to a FileInfo object to take advantage of extra methods
[System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))
# Create the directory if it doesn't already exits
if (!(Test-Path) $destination.Directory.FullName)
{
New-item -Path $destination.Directory.FullName -ItemType Directory
}
# Copy the source to the target directory
copy-item -Path $_.FullName -Destination $Destination.FullName
}
这篇关于powershell根据文件名的一部分移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!