Powershell复制和重命名文件

时间:2017-11-08 21:48:42

标签: powershell copy rename get-childitem

我正在尝试将文件从源文件夹复制到目标文件夹,并在此过程中重命名文件。

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

问题是,如果找不到文件,Get-ChildItem不会抛出错误消息,而只是给你一个空白,我最终会在目标中找到一个名为File01.test的文件夹File*中没有名为$Source的文件。

如果确实存在,复制操作执行得很好。但是如果$Source中不存在匹配的文件,我不希望创建文件夹,而只是想在日志文件中记录错误消息,并且不会发生文件操作。

2 个答案:

答案 0 :(得分:0)

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".

答案 1 :(得分:0)

这不应该是文件名是什么,但它不会考虑目的地中已存在的文件。因此,如果已经存在File01.txt,并且您再次尝试复制File01.txt,那么您将遇到问题。

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'"
    }
}