Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I actually generate an error using $PSCmdlet.WriteError in PowerShell?

I’ve been reading up on generating error messages in PowerShell and stumbled across this example…

$Exception = [Exception]::new("error message")
$ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
    $Exception,
    "errorID",
    [System.Management.Automation.ErrorCategory]::NotSpecified,
    $TargetObject # usually the object that triggered the error, if possible
)
$PSCmdlet.WriteError($ErrorRecord)

However, this isn’t a working example. I can’t start experimenting with it, since I have no idea what would make the example tick to begin with.

InvalidOperation: You cannot call a method on a null-valued expression.

I do know I could use Write-Error to generate a non-terminating error instead. But I really don’t like the error message to echo the command I used to generate the error message.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code looks good, the only problem is that $PSCmdlet is only available for you in the context of an advanced function or script block:

function Testing {
    [CmdletBinding()]
    param($TargetObject)

    $Exception = [Exception]::new('error message')
    $ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
        $Exception,
        'errorID',
        [System.Management.Automation.ErrorCategory]::NotSpecified,
        $TargetObject) # usually the object that triggered the error, if possible

    $PSCmdlet.WriteError($ErrorRecord)
}

Testing foo!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading