复制文件时嵌套try catch
Nested try catch when copying a file
我正在从不包含文件扩展名的 .csv 文件位置复制文件。我试图对有效的“.tif”进行硬编码,但还有其他文件类型被遗漏了。我试图使用下面的,但它抛出一个错误,指出路径显示为 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)"
}
}
如果您一次只有一个匹配文件,这样的方法应该有效:
$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 }
如果这会偶然匹配您不想复制的其他文件(例如 $name
是 "foo" 并且您想复制 "foo.tif" 而不是 "foo.bar.txt" ) 您可以在复制前按基本名称过滤:
Get-ChildItem "${src}.*" | Where-Object {
$_.BaseName -eq $name
} | Copy-Item -Destination { $dst + $_.Extension }
我正在从不包含文件扩展名的 .csv 文件位置复制文件。我试图对有效的“.tif”进行硬编码,但还有其他文件类型被遗漏了。我试图使用下面的,但它抛出一个错误,指出路径显示为 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)"
}
}
如果您一次只有一个匹配文件,这样的方法应该有效:
$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 }
如果这会偶然匹配您不想复制的其他文件(例如 $name
是 "foo" 并且您想复制 "foo.tif" 而不是 "foo.bar.txt" ) 您可以在复制前按基本名称过滤:
Get-ChildItem "${src}.*" | Where-Object {
$_.BaseName -eq $name
} | Copy-Item -Destination { $dst + $_.Extension }