Powershell将重复移动到DUP文件夹

发布于 2025-01-23 17:41:45 字数 1256 浏览 0 评论 0原文

以下是我目前拥有的,并且正在工作。但是,如果我有重复的话,只是吐出错误而不会移动文件。显然。我该如何实现将所述重复文件移至已经存在的文件夹(我不希望它创建一个文件夹)

$srcRoot = "\\networkdrive source"
$dstRoot = "\\networkdrive dst"

# Map to destination subdirectory based on first 2 chars of file name
$map = @{
    '02' = '02 Folder'
    '13' = '13 Folder'
    '30' = '30 Folder'
    '33' = '33 Folder'
    '58' = '58 Folder'
    '82' = '82 Folder'
    '86' = '86 Folder'
}

$fileList = Get-ChildItem -Path $srcRoot -File -Force -Recurse
foreach ($file in $fileList)
{
    $key = $file.BaseName.Substring(1,2)
    if ($key -in $map.Keys)
    {
        $fileName = $file.Name
        $dstDir = Join-Path -Path $dstRoot -ChildPath $map[$key]
        # Create destination directory if needed
        if (-not (Test-Path -Path $dstDir))
        {
            #mkdir -Path $dstDir
        
        }
        Write-Verbose "Moving $($file.FullName)"
        if (Test-Path -Path (Join-Path -Path $dstDir -ChildPath $fileName))
        {
            # Error message if file already exists at destination
            Write-Error -Message "File $fileName already exists at $dstDir"
        } else {
            # OK to move file
            Move-Item -Path $($file.FullName) -Destination $dstDir
        }
    }
}

Below is what I currently have and it is working. However, If I have a duplicate is just spits out an error and doesnt move the file.. obviously. How can I implement to move said duplicate file(s) to a folder that already exists (I dont want it to create a folder)

$srcRoot = "\\networkdrive source"
$dstRoot = "\\networkdrive dst"

# Map to destination subdirectory based on first 2 chars of file name
$map = @{
    '02' = '02 Folder'
    '13' = '13 Folder'
    '30' = '30 Folder'
    '33' = '33 Folder'
    '58' = '58 Folder'
    '82' = '82 Folder'
    '86' = '86 Folder'
}

$fileList = Get-ChildItem -Path $srcRoot -File -Force -Recurse
foreach ($file in $fileList)
{
    $key = $file.BaseName.Substring(1,2)
    if ($key -in $map.Keys)
    {
        $fileName = $file.Name
        $dstDir = Join-Path -Path $dstRoot -ChildPath $map[$key]
        # Create destination directory if needed
        if (-not (Test-Path -Path $dstDir))
        {
            #mkdir -Path $dstDir
        
        }
        Write-Verbose "Moving $($file.FullName)"
        if (Test-Path -Path (Join-Path -Path $dstDir -ChildPath $fileName))
        {
            # Error message if file already exists at destination
            Write-Error -Message "File $fileName already exists at $dstDir"
        } else {
            # OK to move file
            Move-Item -Path $($file.FullName) -Destination $dstDir
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文