-ErrorAction Stop does not work in Copy-Item

Simple script:

"test" | Out-File "C:\existing_file.txt" $ErrorActionPreference = "Continue" Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt" -ErrorAction Stop "hello" | Out-Host 

I have this output:

 Copy-Item : Could not find a part of the path "C:\NonExistingDir\file.txt". C:\Users\ESavin\AppData\Local\Temp\d3d410e0-79b3-4736-b7e7-5aba1ab11a12.ps1:1 :10 + Copy-Item <<<< "C:\existing_file.txt" "C:\NonExistingDir\file.txt" -ErrorAction Stop + CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand hello 

Why do I get hi output? -ErrorAction Stop not working?

update:

this code:

 "test" | Out-File "C:\existing_file.txt" $ErrorActionPreference = "Stop" Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt" "hello" | Out-Host 

worked properly. there is no hello output.

Copy-Item ignore -ErrorAction and use only $ ErrorActionPreference ??

+6
source share
3 answers

As indicated in the help, the ErrorAction parameter does not affect the interruption of errors that you have.

  The ErrorAction parameter has no effect on terminating errors (such as missing data, parameters that are not valid, or insufficient permissions) that prevent a command from completing successfully. 

Source: Get-Help about_commonparameters and http://technet.microsoft.com/en-us/library/dd315352.aspx

+5
source

It’s strange. I copied your two lines in a script, ran it, and everything works fine: I don't see "hi". Your "-ErrorAction" must take precedence over any $ ErrorActionPreference that you would set at the session level.

0
source

You must either run:

 Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt" -ErrorAction Continue "hello" | Out-Host 

or set $ErrorActionPreference="continue" and run

 Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt" "hello" | Out-Host 

These are the only two ways you could get the output you are showing. So make sure that you do what you require.

0
source

Source: https://habr.com/ru/post/908870/


All Articles