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