Home > front end >  Move-Item IF already exist, rename-item?
Move-Item IF already exist, rename-item?

Time:10-07

i have a move-item script in a foreach loop:

this is my source $dateipfad:

Dateipfad
\\FS-SRV01\123\456\35902\20226229.pdf
\\FS-SRV01\123\456\33705\20226829.pdf
\\FS-SRV01\123\456\34188\2022260_065.pdf
\\FS-SRV01\123\456\31204\909862108_106.pdf
Foreach ($i in $dateipfad) {
Move-Item -Path $i.dateipfad -Destination $geloescht -ErrorAction Stop
}

but some filenames could already exist...is there a way to use IF when there is this "already exists" error?

f.e. to rename item "12345.pdf" to "12345-1.pdf and trying to move again?

anything simple i can do?

CodePudding user response:

You can do that by taking the full path and filename from the input file and splitting that into a BaseName and Extension part. Next get a list of all files in the destination directory with similar names and do a loop to build a new destination filename by appending a hyphen and sequence number to the base name if needed.

Try:

# import the file that holds the file paths
$dateipfad = Import-Csv -Path 'X:\WherEverYourInputFileIs\moveThese.csv' 
# set your destination directory
$geloescht = 'X:\PathToDestination'

foreach ($item in $dateipfad) {
    # split each filename into a basename and an extension variable
    $baseName  = [System.IO.Path]::GetFileNameWithoutExtension($item.Dateipfad)
    $extension = [System.IO.Path]::GetExtension($item.Dateipfad)    # this includes the dot
    # get an array of all filenames (names only) of the files with a similar name already present in the destination folder
    $allFiles = @((Get-ChildItem $geloescht -File -Filter "$baseName*$extension").Name)
    # construct the new filename
    $newName = $baseName   $extension
    $count = 1
    while ($allFiles -contains $newName) {
        # as long as the $allFiles array contains the $newName, keep incrementing the $count sequence number
        $newName = "{0}-{1}{2}" -f $baseName, $count, $extension
        $count  
    }
    # use Join-Path to create a FullName for the file and move the file with this new name
    $newFile = Join-Path -Path $geloescht -ChildPath $newName
    Move-Item -Path $item.Dateipfad -Destination $newFile -Force
}
  • Related