ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

前端 未结 3 1971
别跟我提以往
别跟我提以往 2020-12-09 09:09

My case:

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


        
相关标签:
3条回答
  • 2020-12-09 09:35

    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 {
    
    }
    
    0 讨论(0)
  • 2020-12-09 09:38

    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.

    0 讨论(0)
  • 2020-12-09 09:39

    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.

    0 讨论(0)
提交回复
热议问题