How to handle Copy-Item exceptions? How to handle Copy-Item exceptions? powershell powershell

How to handle Copy-Item exceptions?


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 = $_  ...}