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
instead to generate a non-terminating error. But I really don't like the error message to echo the command I used to generate the error message.