2017-03-13 31 views
1

我期待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 
} 

回答

1

請勿修改$nextName。在移動源文件之前重命名目標文件。

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

$_ | Move-Item -Destination $nextName 
+0

很棒的工作。非常感謝Ansgar – Govna

0

我對這一切都很陌生,但請嘗試下面的內容,讓我知道你是否有任何問題?

$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 
} 

這看起來會對我有用,但就像我說的,我還在學習。我試着對它進行評論以解釋每個點發生了什麼