简体   繁体   中英

Powershell copy and rename files

I'm trying to copy files from a source folder to a destination folder, and rename the files in the process.

$Source = "C:\Source"

$File01 = Get-ChildItem $Source | Where-Object {$_.name -like "File*"}

$Destination = "\\Server01\Destination"

Copy-Item "$Source\$File01" "$Destination\File01.test" -Force -
Confirm:$False -ErrorAction silentlyContinue
if(-not $?) {write-warning "Copy Failed"}
else {write-host "Successfully moved $Source\$File01 to 
$Destination\File01.test"}

The problem is that since Get-ChildItem doesn't throw an error message if the file is not found, but rather just gives you a blank, I end up with a folder called File01.test in destination if no file named File* exists in $Source .

If it does exist, the copy operation carries out just fine. But I don't want a folder to be created if no matching files exist in $Source , rather I just want an error message logged in a log file, and no file operation to occur.

You can add an "if" statement to ensure that the code to copy the files only runs when the file exists.

$Source = "C:\Source"
$Destination = "\\Server01\Destination"
$File01 = Get-ChildItem $Source | Where-Object {$_.name -like "File*"}
if ($File01) {
  Copy-Item "$Source\$File01" "$Destination\File01.test" -Force -Confirm:$False -ErrorAction silentlyContinue
  if(-not $?) {write-warning "Copy Failed"}
  else {write-host "Successfully moved $Source\$File01 to 
  $Destination\File01.test"}
} else {
  Write-Output "File did not exist in $source" | Out-File log.log
}

In the "if" block, it will check to see if $File01 has anything in it, and if so, then it'll run the subsequent code. In the "else" block, if the previous code did not run, it'll send the output to the log file "log.log".

This shouldn't matter what the file name is, but it won't account for files that already exist in the destination. So if there is already File01.txt and you're trying to copy File01.txt again you'll have problems.

param
(
    $Source = "C:\Source",
    $Destination = "\\Server01\Destination",
    $Filter = "File*"
)

$Files = `
    Get-ChildItem -Path $Source `
    | Where-Object -Property Name -Like -Value $Filter

for ($i=0;$i -lt $Files.Count;$i++ )
{
    $NewName = '{0}{1:D2}{3}' -f $Files[$i].BaseName,$i,$Files[$i].Extension
    $NewPath = Join-Path -Path $Destination -ChildPath $NewName
    try
    {
        Write-Host "Moving file from '$($Files[$i].FullName)' to '$NewPath'"
        Copy-Item -Path $Files[$i] -Destination 
    }
    catch
    {
        throw "Error moving file from '$($Files[$i].FullName)' to '$NewPath'"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM