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.
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"
}
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 = $_
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With