【问题标题】:How to move files using PowerShell which aren't in the destination folder?如何使用 PowerShell 移动不在目标文件夹中的文件?
【发布时间】:2020-03-30 18:34:03
【问题描述】:

在编写一个 PS 脚本以定期将文件从一个文件夹移动到另一个文件夹以进行处理时,我需要帮助。我已经使用了下面提到的代码,但我不知道如何检查文件是否已经存在于目标中。它存在,则不应复制该文件。请帮忙。

$destination = "C:\Users\User\Desktop\Destination\"
$source = "C:\Users\User\Desktop\Source"
$files = Get-ChildItem $source
Write-Host $files
foreach($file in $files)
{

    $path = "C:\Users\User\Desktop\Source\" + $file
    Move-Item -Path $path -Destination $destination -Force
}

请帮助检查文件是否在目标文件夹中并跳过它移动。

问候,

米特什·阿格拉瓦尔

【问题讨论】:

  • 不确定这是否是重复的,但似乎您可以使用Test-Path 确保在移动之前文件不存在。类似于if (-not(Test-Path -Path $path)){ Move-Item -Path $path -Destination $destination}
  • 使用 robocopy 可能会更容易

标签: powershell


【解决方案1】:

使用带有叶子属性的 Tes-Path 将检查是否存在任何文件。

if !(Test-Path $path -PathType 叶) { 移动项目 -Path $path -Destination $destination -Force }

【讨论】:

    【解决方案2】:

    感谢@kamel。以下代码完美运行。

    $destination = "C:\Users\User1\Desktop\Destination\"
    $source = "C:\Users\User1\Desktop\Source"
    $files = Get-ChildItem $source
    Write-Host $files
    foreach($file in $files)
    {
        $path1 = "C:\Users\User1\Desktop\Source\" + $file
        $path2 = "C:\Users\User1\Desktop\Destination\" + $file
        if (!(Test-Path $path2 -PathType leaf)) 
        { 
        Move-Item -Path $path1 -Destination $destination -Force
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多