Powershell 递归地将子文件夹中的文件夹/文件移动到其父文件夹

Powershell 递归地将子文件夹中的文件夹/文件移动到其父文件夹,powershell,directory,move,parent,relative-path,Powershell,Directory,Move,Parent,Relative Path,我有一个高级文件夹(称为“0级”),其中包含大约100个子文件夹(“1级”),这些子文件夹中包含较低级别的子文件夹和文件(“2级”)。我需要动态地将每个文件和文件夹从“级别2”移动到其级别1子文件夹(或者相对而言,移动到其父文件夹) 为了更好地形象化: Master folder ├ Parent folder 1 │ ├─ Subfolder A │ │ ├─ File A │ │ └─ File B │ ├─ Subfolder B │ │ ├─ File C │ │ └─ File

我有一个高级文件夹(称为“0级”),其中包含大约100个子文件夹(“1级”),这些子文件夹中包含较低级别的子文件夹和文件(“2级”)。我需要动态地将每个文件和文件夹从“级别2”移动到其级别1子文件夹(或者相对而言,移动到其父文件夹)

为了更好地形象化:

Master folder ├ Parent folder 1 │ ├─ Subfolder A │ │ ├─ File A │ │ └─ File B │ ├─ Subfolder B │ │ ├─ File C │ │ └─ File D │ ├─ File E │ └─ File F . . ... many folders more ... . └─ Parent folder 134 ├─ Subfolder CS │ ├─ File AGF │ └─ File ARH ├─ File ROQ └─ File JGL
我确实想为你做点什么。这会将所有内容从level2文件夹移动到level1文件夹。请尝试一下,让我知道它是如何工作的

$master = "C:\Temp\Level0\"
Get-ChildItem $master | ForEach-Object {
    $dest = ($_.fullname)+"\"
    $Loc = (Get-ChildItem $_.FullName | Select-Object -ExpandProperty fullname)+"\*"
    Move-item -Path $Loc -Destination $dest
}

这应该是你想要的。但是,如果文件名已被使用,则不会将具有相同文件名的任何文件移动到父文件夹

$FilePath = Read-Host "Enter FilePath"
$FileSource = Get-ChildItem -Path $FilePath -Directory

foreach ($Directory in $FileSource)
{
    $Files = Get-ChildItem -Path $Directory -File

    foreach ($File in $Files){
        Move-item -Path $File.Fullname -Destination $FilePath
    }
}

希望这会有所帮助。

您已经有了正确的想法,尽管您的代码示例有点不完整(请始终发布一个)。您的问题是,当需要将
$parent
设置为文件夹的完整路径时,将
$parent=$\ucode>设置为该文件夹的完整路径。将该行更改为
$parent=$\ FullName
,您的代码应该可以工作。我在家里(非域计算机)尝试过这一点,它似乎工作正常。但是,在office中使用一些主文件夹内容的副本运行此操作,并将其放在我自己的工作站上,它似乎失败了,正在将数据从当前驱动器的根目录拉到父文件夹。请参阅下一条注释中的以下代码。Move-item:源路径和目标路径必须不同。第6行字符:5+移动项目-路径$Loc-目的地$dest+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~类别信息:WriteError:(D:\Test\Master\…\FOLDER 1:DirectoryInfo)[移动项目],IOException+FullyQualifiederRoId:MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand移动项目:对路径“D:\OneNote”的访问被拒绝。第6行字符:5+移动项目-路径$Loc-目的地$dest+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~类别信息:编写者:我尝试过这个方法,但没有成功,因为目的地是顶级的“主”文件夹,其中包含了所有的“父”子文件夹。我需要所有文件都位于父文件夹下,并移动到父文件夹。
$master = "C:\Temp\Level0\"
Get-ChildItem $master | ForEach-Object {
    $dest = ($_.fullname)+"\"
    $Loc = (Get-ChildItem $_.FullName | Select-Object -ExpandProperty fullname)+"\*"
    Move-item -Path $Loc -Destination $dest
}
$FilePath = Read-Host "Enter FilePath"
$FileSource = Get-ChildItem -Path $FilePath -Directory

foreach ($Directory in $FileSource)
{
    $Files = Get-ChildItem -Path $Directory -File

    foreach ($File in $Files){
        Move-item -Path $File.Fullname -Destination $FilePath
    }
}