【问题标题】:Move item rename original item移动项目重命名原始项目
【发布时间】:2017-03-13 20:46:09
【问题描述】:

我希望 PowerShell 检查文件是否存在于两个位置 - 源文件夹和目标文件夹。如果两者都存在,我希望它将"voided" 附加到目标文件,然后将源文件移动到目标位置。

我发现下面的脚本有效,但它重命名了源文件,而不是目标文件夹中的文件。我已经搜索并厌倦了反转脚本,但在所有情况下我只能让它重命名源文件。我错过了什么?

$src = "c:\Temp\Invoice"
$dest = "c:\Temp\test"
$v = "voided"

Get-ChildItem -Path $src -Filter *.pdf -Recurse | ForEach-Object {
    $nextName = Join-Path -Path $dest -ChildPath $_.name

    while (Test-Path -Path $nextName) {
        $nextName = Join-Path $dest ($_.BaseName + "_$v" + $_.Extension)
    }

    $_ | Move-Item -Destination $nextName
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    不要修改$nextName。在移动源文件之前重命名目标文件。

    if (Test-Path -LiteralPath $nextName) {
      Rename-Item -LiteralPath $nextName -NewName ($_.BaseName + "_$v" + $_.Extension)
    }
    
    $_ | Move-Item -Destination $nextName
    

    【讨论】:

      【解决方案2】:

      我自己对这一切都很陌生,但是请尝试以下方法,如果您有任何问题,请告诉我?

      $sourceFolder = "\\root\source\folder"
      $destinationFolder = "\\root\destination\folder"    
      $v = "voided"    
      
      #Get just the file names for the items in your source folder
      $filesInSource = Get-ChildItem -Path $sourceFolder -Filter *.PDF -Recurse | select Name
      
      
      #join-path will stick the two variables together as a full file path
      Join-Path -Path $destinationFolder -ChildPath $filesInSource | Where-Object {Test-Path $_} | ForEach-Object {
          #Renames the file in the $destinationFolder
          Rename-Item -NewName ($_.BaseName + "_$v" + $_.Extension)
          #Moves the item from the $sourceFolder into the $destinationFolder keeping original name
          Move-Item -Path (Join-Path -Path $sourceFolder -ChildPath $filesInSource) -Destination $destinationFolder
      }
      

      这看起来对我有用,但就像我说的,我还在学习。我试图对此发表评论以解释每一点发生的事情

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-19
        • 2022-10-15
        • 2011-01-03
        • 2014-05-14
        • 2016-08-03
        • 2021-09-20
        • 2022-10-13
        相关资源
        最近更新 更多