gpt4 book ai didi

powershell - 如何在Powershell中为高级功能生成非终止错误

转载 作者:行者123 更新时间:2023-12-03 00:38:50 26 4
gpt4 key购买 nike

我想具有以下功能

function get-diskinfo {
[string[]]$ComputerName
# some stuff here
}

所以我可以像
get-diskinfo -ComputerName com1,com2,com3
if (!$?) { # I want to caller to check this, so the experience is same as built-in cmdlet
write-error "failed to get disk info for some computer"
}

但是,在谷歌搜索之后,仍然不知道如何从get-diskinfo生成非终止错误,怎么做呢?先感谢您!

最佳答案

就目前而言,您的功能不是高级功能。将其更改为高级功能:

function Get-DiskInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[Alias("CN")]
[ValidateNotNull()]
[string[]]
$ComputerName
)
...
}

为了访问 $pscmdlet,必须具有真正的高级功能。要编写一个非终止错误,请使用 $pscmdlet.WriteError()。您可以看中并执行以下操作:
$ex = new-object System.Management.Automation.ItemNotFoundException "Cannot find path '$Path' because it does not exist."
$category = [System.Management.Automation.ErrorCategory]::ObjectNotFound
$errRecord = new-object System.Management.Automation.ErrorRecord $ex, "PathNotFound", $category, $Path
$psCmdlet.WriteError($errRecord)

关于powershell - 如何在Powershell中为高级功能生成非终止错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20392996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com