问题
I have a set of files like this:
2015_09_22
|____ foo
|____ common.ext
|____ common.1.ext
|____ common.2.ext
|____ common.3.ext
|____ bar
|____ common.ext
|____ common.1.ext
|____ common.2.ext
I want to merge them into a structure like this, using the source folder name as a string to prepend to the filename:
2015_09_22
|____ foo_common.ext
|____ foo_common.1.ext
|____ foo_common.2.ext
|____ foo_common.3.ext
|____ bar_common.ext
|____ bar_common.1.ext
|____ bar_common.2.ext
The format of {date}\foo and {date}\bar is fixed but the contents could have a variable number of files with those names.
回答1:
You could use something like:
cd .\2015_09_22\
Get-ChildItem *\* | ForEach {$_.MoveTo("$($_.Directory.Parent.FullName)\$($_.Directory.Name)_$($_.Name)")}
This moves the files, but doesn't remove the directories, and is a little hard to read. So maybe this is more reasonable:
cd .\2015_09_22\
foreach ($dir in (Get-ChildItem -Directory)) {
foreach ($file in (Get-ChildItem $dir -File)) {
$dest = "$($file.Directory.Parent.FullName)\$($file.Directory.Name)_$($file.Name)"
$file.MoveTo($dest)
}
$dir.Delete()
}
来源:https://stackoverflow.com/questions/32728229/using-powershell-to-merge-two-folders-and-rename-files-based-on-source-folder