1

I have list of files, I am trying to copy to another location.

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

So I get an error when file abc.ps1 is not availalbe, Is there a way to Test-Path by avoiding to write a loop and write in single line?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user2934433
  • 343
  • 1
  • 5
  • 20

1 Answers1

3

Filter out the ones that don't exist with Test-Path in Where clause.

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

Or shorthand version of the same script:

$files = @("abc.ps1", "def.ps1")
$files | ?{ Test-Path $_ } | %{ $file = gi $_; cp $file.FullName "destinationlocation\$_" -Force; }
Justinas Marozas
  • 2,482
  • 1
  • 17
  • 37