【问题标题】:Check file exists in source before copying复制前检查源中是否存在文件
【发布时间】:2018-01-20 22:32:37
【问题描述】:

我有文件列表,我正在尝试复制到另一个位置。

$files = @("abc.ps1", "def.ps1")
$scriptFiles | Copy-Item -Destination "destinationlocation" -Force

所以当文件 abc.ps1 不可用时出现错误,有没有办法通过避免编写循环并在单行中写入来Test-Path

【问题讨论】:

  • 循环有什么问题?为什么一定要一行?变量名称不同。
  • 我学习它是为了知识目的

标签: powershell


【解决方案1】:

Where 子句中用Test-Path 过滤掉不存在的那些。

$files = @("abc.ps1", "def.ps1")
$files | Where { Test-Path $_ } | ForEach { $file = Get-Item $_; Copy-Item "destinationlocation\$_" -Force; }

或同一脚本的速记版本:

$files = @("abc.ps1", "def.ps1")
$files | ?{ Test-Path $_ } | %{ $file = gi $_; cp $file.FullName "destinationlocation\$_" -Force; }

【讨论】:

  • 很好,但您可以直接通过管道发送到Copy-Item - 不需要ForEach-Object
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 2020-02-03
  • 2018-02-20
  • 2011-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多