根据文件夹名称将文件夹的内容上移一级

时间:2021-06-29 22:08:36

标签: powershell

我有一个按文档编号分隔的信息目录,因此每个包含文档的文件夹都以 DOC-######-NameOfDocument 开头。我想要做的事情是创建一个 PowerShell 脚本,该脚本将搜索具有指定文档编号的任何文件夹的目录,然后获取该文件夹的内容,将其向上移动一级,然后删除原始文件夹(现在应该为空)。

以下是我得到的最接近预期结果的结果。

$Path = "filepath"
$Folders = Get-ChildItem -Filter "DOC-#####*" -Recurse -Name -Path $Path
$companyID = "######"


    foreach ($Folder in $Folders){
        $filepath = $Path + $Folder
        $Files = Get-ChildItem -Path $filepath

        $imagesourc = $filepath + $companyID
        $imageDest = $filepath.Substring(0, $filepath.LastIndexOf('\'))

            if (Test-Path -Path $imagesourc){
                Copy-Item -Path $imagesourc -Destination $imageDest -Recurse
            }
        

        foreach ($File in $Files){
        
            $Parent_Directory = Split-Path -Path $File.FullName
            $Destination_Path = $filepath.Substring(0, $filepath.LastIndexOf('\'))

            Copy-Item -Path $File.FullName -Destination $Destination_Path -Recurse
               if ($null -eq (Get-ChildItem -Path $Parent_Directory)) {  
            }
        }
        Remove-Item $filepath -Recurse
    }

这可以满足我的需求,但无论出于何种原因我无法 Devine,它都无法在 .HTM 文件上运行。我要移动的大多数文件都是 .html 和 .htm 文件,所以我也需要让它与 .htm 一起使用。 .HTM 文件不会移动,文件夹也不会被删除,这至少是好的。

1 个答案:

答案 0 :(得分:0)

试试这个:

$ErrorActionPreference = 'Stop'
$fileNumber = '1234'
$initialFolder = 'X:\path\to\folders'

$folders = Get-ChildItem -Path $initialFolder -Filter DOC-$fileNumber* -Force -Directory -Recurse

foreach($folder in $folders)
{
    try
    {
        Move-Item $folder\* -Destination $folder.Parent.FullName
        Remove-Item $folder
    }
    catch [System.IO.IOException]
    {
        @(
            "$_".Trim()
            "File FullName: {0}" -f $_.TargetObject
            "Destination Folder: {0}" -f $folder.Parent.FullName
        ) | Out-String | Write-Warning
    }
    catch
    {
        Write-Warning $_
    }
}

重要说明:

  • Move-Item $folder\* 将递归移动所有文件夹内容。如果 $folder 中有文件夹,它们也将被移动,如果您想定位有文件的文件夹,则应在此 cmdlet 之前添加 if 条件.
  • Try {...} Catch {...} 主要是处理文件冲突,如果父文件夹中已经存在同名文件,它会通知你并且不会移动也不会文件夹被删除。
  • -Filter DOC-$fileNumber* 将捕获所有以 $fileNumber 中的数字命名的文件夹,但要小心,因为它可能捕获您可能不打算删除的文件夹。
    • 示例:如果您想获取包含编号 1234 (DOC-12345-NameOfDocument, DOC-12346-NameOfDocument, ...) 的所有文件夹,但您不想捕获 DOC-12347-NameOfDocument 那么你应该微调过滤器。或者您可以添加 -Exclude 参数。
  • -Force & -Directory 获取隐藏文件夹并定位文件夹。
相关问题