Powershell 复制前检查源中是否存在文件

Powershell 复制前检查源中是否存在文件,powershell,Powershell,我有文件列表,我正在尝试复制到其他位置 $files = @("abc.ps1", "def.ps1") $scriptFiles | Copy-Item -Destination "destinationlocation" -Force 因此,当abc.ps1文件不可用时,我得到了一个错误。那么,有没有办法通过避免写循环和单行来测试路径呢?过滤掉Where子句中不存在的那些 $files = @("abc.ps1", "def.ps1") $files | Where { Test-Path

我有文件列表,我正在尝试复制到其他位置

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

因此,当abc.ps1文件不可用时,我得到了一个错误。那么,有没有办法通过避免写循环和单行来测试路径呢?

过滤掉
Where
子句中不存在的那些

$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; }

循环有什么问题?为什么必须是一行?变量名称各不相同。我学习它是为了获取知识,但您可以直接通过管道连接到
复制项
——无需为每个对象。