Reputation: 401
Below is a simple Try Catch
but when I was testing it, when successful it appears to file so I included a location which didnt exist into the variable to test the failure, but oddly even though the failure appears in the ISE window the out still shows as suceeded maing something isnt quite right with below, any ideas as Im lost at what is wrong.
## The location/filename where the Logs will be stored
$varfullpath = "I:\Dev\BI\Reference Data\Release_Event_log.txt"
## The location/filename of the Source to copy from
$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\kljhkjlOS\"
## The location/filename of the Destination to copy to
$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\OkjhkhDS\"
$Server = "CHH-BITEST"
$CurrentDate = Get-Date
try{
Get-ChildItem -Path $sourceDirectory -File -Filter "*.csv" | Copy-Item -Destination $destinationDirectory -ErrorAction Stop
Write-Log -Message "Copy from $sourceDirectory to $destinationDirectory suceeded" -path $varfullpath
}
catch{
$Error[0] | Write-Log -path $varfullpath
Write-log -Message "Copy from $sourceDirectory to $destinationDirectory Failed" -Level Error -path $varfullpath
}
Start-Process notepad $varfullpath ## Opens the file immediately for review
Upvotes: 3
Views: 73
Reputation: 11254
Some additions to @guiwhatsthat's answer:
PowerShell distinguishes between terminate errors and non-terminating errors. With the help of the common ErrorAction
parameter you can setup the behaviour of a cmdlet if such kind of error occurrs. If you want to change the behaviour of multiple cmdlets, or sections in your script you can change the value of $ErrorActionPreference
.
From PowerShell documentation:
$ErrorActionPreference
Determines how PowerShell responds to a non-terminating error (an error that does not stop the cmdlet processing) at the command line or in a script, cmdlet, or provider, such as the errors generated by the Write-Error cmdlet.
You can also use the ErrorAction common parameter of a cmdlet to override the preference for a specific command.
Valid values:
Stop: Displays the error message and stops executing.
Inquire: Displays the error message and asks you whether you want to continue.
Continue: Displays the error message and continues (Default) executing.
Suspend: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed.
SilentlyContinue: No effect. The error message is not displayed and execution continues without interruption.
Upvotes: 2
Reputation: 2434
The error is thrown by the get-childitem
command.
Add the -ErrorAction Stop to this command like that:
Get-ChildItem -Path $sourceDirectory -File -Filter "*.csv" -ErrorAction Stop | Copy-Item -Destination $destinationDirectory -ErrorAction Stop
Upvotes: 2