【问题标题】:Using a test-path within a copy-item in PowerShell?在 PowerShell 的复制项中使用测试路径?
【发布时间】:2019-11-14 21:01:08
【问题描述】:

我目前正在将一个文件(从通过 SQL 表中的列设置的变量 $_.'File Path')复制到另一个文件夹位置 ($Path)。

$_.'File Path' 变量包括文件夹位置、文件名,但不包括扩展名。我想通过测试路径设置扩展,但我很难做到。

例如测试$_.'File Path' 是否具有.PDF 的扩展名,如果是,请复制。 如果没有,请测试$_.'File Path' 是否具有.doc 的扩展名,如果是,请复制。 如果没有,请测试$_.'File Path' 是否有 .tif……..

的扩展名
    Echo "Copying document and Prepending Document Date"
     $copy = [IO.FileInfo]$_.'File Path'
     $copy | Copy-Item -Destination "$path\$($_.'Date')_$($copy.Name)"

【问题讨论】:

  • 你试过Get-Item -Path $YourPath.*吗?如果您的无扩展名路径是唯一的,则通配符将获取完整的文件名。
  • 你不能$copy.Extension吗?然后在 if 语句中:if($copy.Extension -eq ".PDF") { #Copy Item}

标签: powershell copy-item


【解决方案1】:

尝试以下方法:

$extensions = '.pdf', '.doc', '.tif' # add additional extensions as needed

# Create paths with prefix $_.'File-Path' with all the extensions.
# E.g., if $_.'File-Path' contains 'c:\path\to\document', this
# creates the following array:
#   'c:\path\to\document.pdf', 'c:\path\to\document.doc', 'c:\path\to\document.tif'
$filePathsToTest = $extensions -replace '^', [regex]::Escape($_.'File-Path')

# ...

# See if any of the constructed file paths exist.
if ($existingFiles = Get-Item -ErrorAction Ignore $filePathsToTest) { 
  Copy-Item -LiteralPath $existingFiles `
            -Destination "$path\$($_.'Date')_$(Split-Path -Leaf $_.'File-Path')"
}

【讨论】:

  • 这会像以前一样创建文件夹,但不会复制文件。
  • @LFuller:我不确定你在评论中说什么,但我重新阅读了这个问题并大幅修改了答案 - 请再看看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多