powershell - 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)"
}
}
解决方案
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 }
推荐阅读
- javascript - 使用html将新的li html附加到页面时无法准确获取li标签的高度
- sql - 带有动态最后的 Spark 高级窗口
- php - 重新说明 php 的 feof() 是如何工作的
- testing - 如何启动和暂停 jmeter 测试计划运行
- flutter - 颤动的 StaggeredGridView 在条件下显示图块
- macos - macOS 下使用 pip install pytorch 失败
- amazon-web-services - AWS DynamoDB 与 AWS DocumentDB(新推出的服务)之间的区别?
- jquery - VisJS 网络未居中
- highcharts - Highcharts:从底部渲染条形图
- javascript - Angular 动态表单的问题