【问题标题】:Powershell copy and rename filesPowershell 复制和重命名文件
【发布时间】:2018-04-21 18:20:26
【问题描述】:

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

$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 的文件夹987654324@ 存在于$Source 中。

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

【问题讨论】:

    标签: powershell copy rename get-childitem


    【解决方案1】:

    文件名是什么无关紧要,但它不会考虑目标中已存在的文件。因此,如果已经存在 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'"
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以添加“if”语句以确保复制文件的代码仅在文件存在时运行。

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

      在“if”块中,它将检查 $File01 中是否有任何内容,如果有,则运行后续代码。在“else”块中,如果前面的代码没有运行,它会将输出发送到日志文件“log.log”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 2019-02-04
        • 1970-01-01
        • 2016-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多