1

您好,我尝试使用 cath 处理来自 dism 的错误.. 但这并没有那么好。所以我的问题是,我该如何改进它。

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"
    }
} 

对不起我的翻译我翻译得很快^^

提前致谢

4

1 回答 1

0

终止错误仅影响 .NET 库中引发的 PowerShell 函数和异常。如果要检查外部命令(例如可执行文件)的结果,则需要检查变量,其作用与批处理脚本$LASTEXITCODE中的变量相同。%ERRORLEVEL%例如:

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}"
}

另外,不要调用Out-Default您的代码。它不是为此用途而设计的。

于 2020-01-15T23:52:05.423 回答