ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

StackOverflow https://stackoverflow.com/questions/15545429

سؤال

My case:

$ErrorActionPreference = "Stop";
"1 - $ErrorActionPreference;"
Get-ChildItem NoSuchFile.txt -ErrorAction SilentlyContinue;
"2 - $ErrorActionPreference;"
Get-ChildItem NoSuchFile.txt -ErrorAction Stop;
"3 - $ErrorActionPreference;"

Output:

1 - Stop;
2 - Stop;
and display an error...

Now,

$ErrorActionPreference = "Stop";
"1 - $ErrorActionPreference;"
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
"2 - $ErrorActionPreference;"

Output:

1 - Stop;
and display an error...

Why doesn't work -ErrorAction SilentlyContinue) for Get-PSSessionConfiguration ?

Update:

Now,

$ErrorActionPreference = "Continue"
"1 - $ErrorActionPreference;"
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
"2 - $ErrorActionPreference;"

Output:

1 - Continue;
2 - Continue;

Now,

$ErrorActionPreference = "SilentlyContinue"
"1 - $ErrorActionPreference;"
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
"2 - $ErrorActionPreference;"

Output:

1 - SilentlyContinue;
2 - SilentlyContinue;

This reference:

The ErrorAction ubiquitous parameter can be used to silence non-terminating errors using the parameter value SilentlyContinue and it can be used to convert non-terminating errors to terminating errors using the parameter value Stop. However it can't help you ignore terminating errors and in this case Stop-Transcript is throwing a terminating error. If you want to ignore, use a try/catch e.g.:

try { Stop-Transcript } catch {}
هل كانت مفيدة؟

المحلول

A solution for me:

$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
   WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {        
   #Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference 

Or use try-catch

try { 

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)

} 
catch {

}

نصائح أخرى

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top