I'm running the exact same code on three computers. On computer "A" which is PSV2 (which I'm not allowed to upgrade to PSV3), the following code doesn't do anything EXCEPT print the error Message at the end of execution.
$ErrorActionPreference = "Stop"
TRY { $ErrorActionPreference = "Stop"
New-Item -Type File $("C:\Windows\System32\NewFile.Txt") -ErrorAction Stop }
CATCH [System.UnauthorizedAccessException],[System.UnauthorizedAccessException]
{ Write "Rerun with elevated permissions" }
FINALLY { Get-ChildItem $("C:\Windows\System32\new*") }
Message at the side of the screen says I can't add images so this just became interesting...
PS C:\Temp> $ErrorActionPreference = "Stop"
PS C:\Temp> TRY { $ErrorActionPreference = "Stop"
>> New-Item -Type File $("C:\Windows\System32\NewFile.Txt") -ErrorAction Stop }
>> CATCH [System.UnauthorizedAccessException],[System.UnauthorizedAccessException] { Write "Rerun with elevated permissions" }
>> FINALLY { Get-ChildItem $("C:\Windows\System32\new*") }
>>
Directory: C:\Windows\System32
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/13/2009 9:41 PM 313856 newdev.dll
-a--- 7/13/2009 9:39 PM 76288 newdev.exe
New-Item : Access to the path 'C:\Windows\System32\NewFile.Txt' is denied.
At line:2 char:15
+ New-Item <<<< -Type File $("C:\Windows\System32\NewFile.Txt") -ErrorAction Stop }
+ CategoryInfo : PermissionDenied: (C:\Windows\System32\NewFile.Txt:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
Anyway, on Computers "B" & "C" which are PSV3/PSV4 respectively, it works as expected giving the following
PS C:\temp> `$ErrorActionPreference = "Stop"`
PS C:\temp> `TRY { $ErrorActionPreference = "Stop"`
>> `New-Item -Type File $("C:\Windows\System32\NewFile.Txt") -ErrorAction Stop }`
>> `CATCH [System.UnauthorizedAccessException],[System.UnauthorizedAccessException] { Write "Rerun with elevated permissions" }`
>> `FINALLY { Get-ChildItem $("C:\Windows\System32\new*") }`
>>
Rerun with elevated permissions
Directory: C:\Windows\System32
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/13/2009 9:41 PM 313856 newdev.dll
-a--- 7/13/2009 9:39 PM 76288 newdev.exe
PS C:\temp>
As you can see in the source code above. The $ErrorActionPreference line is there outside the try block as well as inside the try block in addition to the -Erroraction Stop on the command itself, and on the V2 computers it isn't working, while the V3/V4 machines it is.
Better than 98% of the machines are PSv2 and for reasons no one has yet shared we are not allowed to upgrade them.
Any thoughts or ideas are welcome. Thank you,