Powershell函数中的错误处理

时间:2013-11-16 04:42:03

标签: powershell error-handling

我正在尝试修改我编写的脚本,模块化,而我学习更多关于工具制作的知识。我正处于试图让它处理错误并且不知道如何使函数突破的地步。这就是我所拥有的:

[CmdletBinding()]
param(
    [string]$DPMServerName = 'server1'
)

Function Get-Libraries {
    Write-Verbose ("Getting list of libraries connected to {0}." -f $DPMServerName)
    Try {
       Set-Variable -Name libraries -Value (Get-DPMLibrary $DPMServerName -ErrorAction Stop | Where {$_.IsOffline -eq $False})
    }
    Catch [Microsoft.Internal.EnterpriseStorage.Dls.Utils.DlsException] {
        Write-Error ("Cannot connect to the DPM library. It appears that the servername is not valid. The specific error message is: {0}" -f $_.Exception.Message)
        Return $_.Exception.Message
    }
    Catch {
        Write-Error ("Unknown error getting library. The specific error message is: {0}" -f $_.Exception.Message)
        Return
    }

    Foreach ($library in $libraries) {
        Write-Verbose ("Starting fast inventory on {0}" -f $library)
        Start-DPMLibraryInventory -DPMLibrary $library -FastInventory -ErrorAction SilentlyContinue
    }

    $libraries
}

Function Update-TapeStatus ($libs) { <### add parameter "$libs" to the function ###>
    Foreach ($library in $libs) {
        $tapes = Get-DPMTape -DPMLibrary $library | Where {$_.Location -notmatch "*slot*"} | Sort Location
        <### output the list of tapes ###>
        $tapes
    }
}

$liblist = Get-Libraries
If ($LASTEXITCODE) { 
    Write-Output $LASTEXITCODE
}
Else {
    Update-TapeStatus $liblist
}

如果出现错误(例如获取库列表),我想呈现自定义消息并停止脚本。我想为其他功能做类似的事情。虽然它写的方式,我没有得到所需的信息。

如何让这项工作?感谢。

1 个答案:

答案 0 :(得分:0)

根据您的澄清,抛出异常的时间是什么,PowerShell正在尝试将异常的类型与您在catch子句中指定的类型进行匹配。

我对DPM模块/管理单元没有任何经验,但我想知道模块是否实际加载了包含您尝试捕获到应用程序域的异常类型的程序集。由于你得到的错误,它似乎没有。希望您知道包含此类的程序集名称是什么。使用Add-Type cmdlet和脚本顶部的-AssemblyName参数来加载程序集,以便PowerShell运行时知道您要查找的异常类型。

作为最后一点,在Microsoft.Internal命名空间中使用类可能不是一个好主意,因为它不是直接在代码中使用,而是作为teh .Net库中的幕后支持。微软可以在没有任何警告的情况下从你身下拉出地毯。

相关问题