1

Hello I tried to handle the errors from dism with cath.. but that didn't work that good. So my question is, how i can improve it.

function dotnet35 () {
    WriteLogNewScirpt "dotnet35"
    WriteLogInstruction "installing .Net 3.5 online"
    $Errorccured=$false
    $Error.Clear()
    try {
    $ErrorActionPreference = 'stop'
        Start-Process -FilePath powershell.exe -ArgumentList {DISM /Online /Enable-Feature /FeatureName:NetFx3 /All} -verb RunAs -WindowStyle Hidden | Out-Default
    } catch {
        WriteLogError ".Net 3.5 could not be installed"
        WriteLogError "$Error"
        $Errorccured=$true  
    }
    if(!$Errorccured) {
        WriteLogPosisitive ".Net 3.5 installed"       
    } else {
        dotnet35offline
    }
}

function dotnet35offline () {
    WriteLogInstruction "installing .Net 3.5 offline"
    $Erroroccured=$false
    $Error.Clear()
    try {
        $ErrorActionPreference = 'stop'
        Start-Process -FilePath powershell.exe -ArgumentList {DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:c:\scripts\sources\features\sxs} -verb RunAs | Out-Default
    } catch {
        WriteLogError ".Net 3.5 could not be installed"
        WriteLogError "$Error"
        $Erroroccured=$true
    }
    if(!$Erroroccured) {
        WriteLogPosisitive ".Net 3.5 konnte offline installiert werden"
    }
} 

Sorry for my translation i translated it quiet fast ^^

thanks in advance

Compo
  • 36,585
  • 5
  • 27
  • 39
ItzImmmy
  • 27
  • 6
  • Put `$ErrorActionPreference = 'stop'` BEFORE you enter the `try{}` block – Theo Dec 18 '19 at 14:22
  • 1
    As currently written, the `Try-Catch-Finally` statement handles merely errors of `Start-Process` cmdlet itself (not inside a child process started). Simply restart the script elevated and omit the `Start-Process` i.e. use `Try {dism …}`. – JosefZ Dec 18 '19 at 16:19

1 Answers1

0

Terminating errors only affect PowerShell functions and exceptions thrown in .NET libraries. If you want to check the result of an external command (such as an executable), you will need to check the $LASTEXITCODE variable, which serves the same purpose as the %ERRORLEVEL% variable in batch scripts. For example:

Start-Process -FilePath dism.exe -ArgumentList '/Online', '/Enable-Feature', '/FeatureName:NetFx3', '/All' -Verb RunAs -WindowStyle Hidden
if( $LASTEXITCODE -ne 0 ){
  # Handle the error here
  # For example, throw your own error
  throw "dism.exe failed with exit code ${LASTEXITCODE}"
}

Also, don't call Out-Default in your code. It's not designed for this use.

codewario
  • 19,553
  • 20
  • 90
  • 159