Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Copy-Item exceptions?

I am writing a PowerShell script which uses Copy-Item. I would like to know what kind of exception will be thrown when Copy-Item fails to copy the files from source to destination?

From this link, I don't see what kind of exception will be thrown.

I want to handle the exception in case of failure.

like image 888
n179911 Avatar asked Sep 22 '15 21:09

n179911


2 Answers

Add the tag "-errorAction stop" to the Copy-Item call, within a Try-Catch, like below. The errorAction throws an error which the Try-Catch can handle.

$filepathname = 'valid file path and name'
$dest = '\DoesntExist\'

try
{
    Copy-Item $filepathname $dest  -errorAction stop
    Write-Host "Success"
}
catch
{
    Write-Host "Failure"
}
like image 158
Dan S Avatar answered Sep 30 '22 09:09

Dan S


Since PowerShell is based on .NET I would expect the exceptions that are defined for the CopyTo() and CreateSubdirectory() methods:

  • ArgumentException
  • ArgumentNullException
  • DirectoryNotFoundException
  • IOException
  • NotSupportedException
  • PathTooLongException
  • SecurityException
  • UnauthorizedAccessException

However, in PowerShell I would simply catch all exceptions indiscriminately (unless you want to handle specific scenarios):

try {
  Copy-Item ...
} catch {
  $exception = $_
  ...
}
like image 40
Ansgar Wiechers Avatar answered Sep 30 '22 08:09

Ansgar Wiechers