首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从PowerShell cmdlet返回错误的最佳做法是什么?

从PowerShell cmdlet返回错误的最佳做法是什么?
EN

Stack Overflow用户
提问于 2015-05-13 20:17:28
回答 3查看 5.8K关注 0票数 3

我正在为我们的应用程序配置需求编写一个基于PowerShell的XML模块。以下是其中一个函数。

代码语言:javascript
运行
复制
<#
.Synopsis
   To update an XML attribute value
.DESCRIPTION
   In the XML file for a particular attribute, if it contains valueToFind then replace it with valueToReplace
.EXAMPLE

-------------------------------Example 1 -------------------------------------------------------------------
   Update-XMLAttribute -Path "C:\web.Config" -xPath "/configuration/system.serviceModel/behaviors/serviceBehaviors/behavior/serviceMetadata" -attribute "externalMetadataLocation" -valueToFind "http:" -ValueToReplace "https:"

   Look for the XPath expression with the attribute mentioned and search whether the value contains "http:". If so, change that to "https":
.EXAMPLE

-------------------------------Example 2 -------------------------------------------------------------------
   Update-XMLAttribute -Path "C:\web.Config" -xPath "/configuration/system.serviceModel/behaviors/serviceBehaviors/behavior/serviceMetadata" -attribute "externalMetadataLocation" -valueToFind "http:" -ValueToReplace "https:"

   Same as Example 1 except that the attribute name is passed as part of the XPath expression

#>
function Update-XMLAttribute
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Web configuration file full path
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$Path,

        # XPath expression up to the parent node
        [string] $xPath,
        # This parameter is optional if you mentioned it in xPath itself
        [string] $attribute,

        [string] $valueToFind,

        [string] $ValueToReplace
    )

    Try
    {
        If (Test-path -Path $Path)
        {
                    $xml = New-Object XML
                    $xml.Load($Path)

                    # If the xPath expression itself contains an attribute name then the value of attribute will be processed and taken
                    If ($xPath.Contains("@")) {
                        $xPath, $attribute = $xPath -split '/@', 2
                    }

                    # Getting the node value using xPath
                    $Items  = Select-Xml -XML $xml -XPath $xPath
                    ForEach ($Item in $Items)
                    {

                        $attributeValue = $Item.node.$attribute
                        Write-Verbose "Attribute value is $attributeValue "

                        if ($attributeValue.contains($valueToFind)) {


                            Write-Verbose "In the attribute $attributeValue - $valueToFind is to be repalced with $ValueToReplace"
                            $Item.node.$attribute = $attributeValue.replace($valueToFind, $ValueToReplace)
                        }
                    }

                    $xml.Save($Path)
                    Write-Verbose " Update-XMLAttribute is completed successfully"
        }
        Else {
            Write-Error " The $path is not present"
        }

    }
    Catch {
        Write-Error "$_.Exception.Message"
        Write-Error "$_.Exception.ItemName"
        Write-Verbose " Update-XMLAttribute is failed"
    }
} # End Function Update-XMLAttribute

由于这个cmdlet将被许多人使用,我不认为简单地写入控制台将是正确的方法。

到目前为止,在我的脚本中,如果没有错误,我可以假定我的脚本已经成功完成。

从PowerShell cmdlet获取结果以便使用者知道它是否成功完成的标准做法是什么?

EN

回答 3

Stack Overflow用户

发布于 2015-05-13 20:30:55

标准的做法是抛出异常。每种不同类型的错误都有单独的异常类型,可用于进一步诊断。

假设没有表示文件,您可以这样做:

代码语言:javascript
运行
复制
if (-not (Test-Path $file))
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

您的cmdlet应记录它将引发的所有可能的异常以及引发的时间。

票数 7
EN

Stack Overflow用户

发布于 2015-05-13 20:30:47

如果你的函数遇到错误,它应该是throw。让调用者决定如何处理错误(忽略、记录消息、终止等等)。

票数 3
EN

Stack Overflow用户

发布于 2015-05-14 01:36:39

虽然您可以抛出异常( PowerShell将捕获该异常并将其包装在ErrorRecord中),但是使用ThrowTerminatingError方法可以获得更大的灵活性。这是基于C#的cmdlet的典型方法。

代码语言:javascript
运行
复制
ThrowTerminatingError(new ErrorRecord(_exception, _exception.GetType().Name, ErrorCategory.NotSpecified, null));

这允许您选择错误类别并提供目标对象。顺便说一句,上面的内容不是我所说的cmdlet。Cmdlet是经过编译的C# (通常)。你所拥有的是一个高级功能。:-)

从高级函数中,您可以像这样访问此方法:

代码语言:javascript
运行
复制
$pscmdlet.ThrowTerminatingError(...)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30214523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档