n179911
n179911

Reputation: 20301

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.

Upvotes: 12

Views: 29917

Answers (2)

Dan S
Dan S

Reputation: 321

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"
}

Upvotes: 21

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

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

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

try {
  Copy-Item ...
} catch {
  $exception = $_
  ...
}

Upvotes: 3

Related Questions