使用 Powershell 将文件夹结构中的文件复制到它们各自的子文件夹

Copy files in a folder structure to their respective sub-folder with Powershell

我想将每个文件夹中的文件 "file_to_move.txt" 移动到各自的 "done" 文件夹。

所以 file_to_move.txtC:\Temp\test\folder1 移动到 C: \Temp\test\folder1\完成 file_to_move.txtC:\Temp\test\folder2 移动到 C:\Temp\test\folder2\完成

...等等,最好在文件名中添加 %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 with a filter to retrieve all file_to_move.txt files recursively from a path. Use the Foreach-Object (alias foreach) to iterate over them and combine the new path using the Join-Path cmdlet. To Copy the Item, you can use the 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 属性 连接文件名。我将把它作为练习留给你。