1

I want to have some function like below

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

so I can use it like

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

however after googling, still no idea to generate non terminating error from get-diskinfo, any idea how to do this? thank you in advance!

2 Answers 2

4

As it stands, your function isn't an advanced function yet. Change it to this to make it an advanced function:

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

Being a real advanced function is necessary in order to get access to $pscmdlet. To write a non-terminating error use $pscmdlet.WriteError(). You can get fancy and do something like this:

$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)
Sign up to request clarification or add additional context in comments.

Comments

1

In general, use the Write-Error cmdlet to create non-terminating errors, or as Keith showed you, use the pscmdlet.WriteError method. In any case, you must catch any terminating errors that occurred in your code, use the try and catch blocks, and instead emit non-terminating errors using one of the above methods.

For more information see the about_Try_Catch_Finally help topic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.