[英]Copy files in a folder structure to their respective sub-folder with Powershell
我想将每个文件夹中的文件“ file_to_move.txt”移动到它们各自的“完成”文件夹中。
所以file_to_move.txt在C:\\ TEMP \\测试\\ folder1中移动到C:\\ TEMP \\测试\\ folder1中\\完成 ,用C file_to_move.txt:\\ TEMP \\测试\\文件夹2移动到C:\\ TEMP \\测试\\ folder2 \\ done
...依此类推,最好在文件名中添加%date%_%time%。
如果文件夹(如下面的示例中的folder4)没有file_to_move.txt,则脚本应忽略它并继续前进。
文件夹结构示例:
即使我不太擅长于Powershell脚本,我也进行了试验,但我不知道它可以用标准的批处理脚本来完成。 到目前为止,我已经尝试过了:
在批处理脚本中:
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%bin\movescript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'"
在movescript.ps1中:
Move-Item C:\Temp\test\*\file_to_move.txt C:\Temp\test\*\done\file_to_move_$(get-date -f yyyyMMdd_HHmmss).txt
但这是行不通的。 我猜这还不够精确。
另外,可以在基本脚本内完成全部操作,还是必须使用外部.PS1-文件?
您可以将Get-ChildItem cmdlet与过滤器一起使用,以从路径递归检索所有file_to_move.txt
文件。 使用Foreach-Object (别名foreach)对它们进行迭代,并使用Join-Path cmdlet合并新路径。 若要复制项目,可以使用Copy-Item cmdlet:
$itemsToCopy = Get-ChildItem -Path c:\Temp\Test -Filter file_to_move.txt -Recurse
$itemsToCopy | foreach {
$newPath = Join-Path $_.DirectoryName 'done'
New-Item -Path $newPath -ItemType directory -Force | out-null
$_ | Copy-Item -Destination $newPath
}
如果要添加时间戳,则可以使用Get-Date cmdlet并以所需的格式调用ToString
方法,例如:
(Get-Date).ToString("yyyy-dd-M_HH-mm-ss")
输出:
2016-05-4_15-06-02
现在,您可以在foreach循环中使用格式字符串以及$_.Basename
和$_.Extension
$_.Basename
属性来连接文件名。 我将把它作为练习留给您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.