PowerShell - Setting $ErrorActionPreference for the entire script

前端 未结 1 651
耶瑟儿~
耶瑟儿~ 2021-02-05 14:05

I\'ve been giving PowerShell (v3.0) a shot for the first time today, and became enormously frustrated with the strange way some of its error-handling concepts are implemented.

1条回答
  •  余生分开走
    2021-02-05 14:12

    Since you're running V3, you also have the option of using $PSDefaultParameterValues:

    $PSDefaultParameterValues += @{'New-RegKey:ErrorAction' = 'Stop'}
    

    Normally that will change it in the global scope. If you want to isolate it to just the local or script scope, you can initialize a new one in the local scope first:

    $PSDefaultParameterValues = @{}
    $PSDefaultParameterValues += @{'New-RegKey:ErrorAction' = 'Stop'}
    

    If you want to inherit what's already in the parent scope and then add to it for the local scope:

     $PSDefaultParameterValues = $PSDefaultParameterValues.clone()
     $PSDefaultParameterValues += @{'New-RegKey:ErrorAction' = 'Stop'}
    

    To set the default ErrorAction for all cmdlets, not just New-RegKey, specify '*:ErrorAction' instead of 'New-RegKey:ErrorAction' in the code above.

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