首页 > 解决方案 > Nested try catch when copying a file

问题描述

I'm copying files from a file location in a .csv, which doesn't contain the extension of the file. I attempted to hard code '.tif' which worked, but there are other file types which are being missed. I attempted to use the below, but it throws an error, stating that the path is showing as C:\users...

    if (-not (Test-Path -Path $path -PathType Container)) {
        New-Item -Path $path -ItemType Directory >$null
    }
    #Perform Copy
    echo "Copying document and Prepending Document Date"

    try {
        $copy = [IO.FileInfo]$_.'Document File Path'+'.tif'
        $copy | Copy-Item -Destination "$path\$($_.'Document Date')_$($copy.Name)"
    } catch {
        try {
              $copy = [IO.FileInfo]$_.'Document File Path'+'.pdf'
              $copy | Copy-Item -Destination "$path\$($_.'Document Date')_$($copy.Name)"
        } catch {
            $copy = [IO.FileInfo]$_.'Document File Path'+'.jpg'
            $copy | Copy-Item -Destination "$path\$($_.'Document Date')_$($copy.Name)"
        } finally {
            $copy = [IO.FileInfo]$_.'Document File Path'+'.doc'
            $copy | Copy-Item -Destination "$path\$($_.'Document Date')_$($copy.Name)"
        }
    } finally {
        $copy = [IO.FileInfo]$_.'Document File Path'+'.docx'
        $copy | Copy-Item -Destination "$path\$($_.'Document Date')_$($copy.Name)"
    }
}

标签: powershelltry-catchcopy-item

解决方案


Something like this should work if you have only one matching file at a time:

$name = Split-Path -Leaf $_.'Document File Path'
$src  = $_.'Document File Path'
$dst  = Join-Path $path ('{0}_{1}' -f $_.'Document Date', $name)
Get-ChildItem "${src}.*" | Copy-Item -Destination { $dst + $_.Extension }

If that would incidentally match other files that you don't want to copy (e.g. $name is "foo" and you want to copy "foo.tif" but not "foo.bar.txt") you could filter by basename before copying:

Get-ChildItem "${src}.*" | Where-Object {
    $_.BaseName -eq $name
} | Copy-Item -Destination { $dst + $_.Extension }

推荐阅读