mnaoumov
mnaoumov

Reputation: 2227

Get a line number where Write-Error occurred

Consider the script

$someComplexCondition = $false

if ($someComplexCondition)
{
    Write-Error -Message "Some complex condition"
}
else
{
    Write-Error -Message "Other complex condition"
}

When I run it it says

C:\Dev> .\MyScript.ps1
C:\Dev\MyScript.ps1 : Other complex condition
At line:1 char:15
+ .\MyScript.ps1 <<<<
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,MyScript.ps1

And I noticed that Write-Error always reports itself as at line:1 According to the stack trace it looks like it's line #1 because it was called from the shell and more interesting char:15 because

".\MyScript.ps1 ".Length -eq 15

If we change file name, this char:15 will be changed accordingly.

The question is how to get the actual line when the error occurred.

In our case I would like to get line:9

Upvotes: 1

Views: 2319

Answers (1)

Mathieu Buisson
Mathieu Buisson

Reputation: 1413

When there is an actual error, generated by Powershell you get an object of the type ErrorRecord :

$error[0] | Get-Member

    TypeName: System.Management.Automation.ErrorRecord

When you use this same ErrorRecord with Write-Error, you don't get an object :

$myError = Write-Error -ErrorRecord $Error[0]
PS C:\> $MyError | Get-Member
gm : You must specify an object for the Get-Member cmdlet.
At line:1 char:12
+ $MyError | gm
+            ~~
    + CategoryInfo          : CloseError: (:) [Get-Member], InvalidOperationException
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand

So now, we know that Write-Error will not give us anything that we can reuse later.

You can use the "Throw" statement, instead :

$someComplexCondition = $false

if ($someComplexCondition)
{
    Throw "Some complex condition"
}
else
{
    Throw "Other complex condition"
}

Then, when you run the script, the error gives you the line number and character number of the start of the "Throw" statement :

C:\Test-Error.ps1
Other complex condition
At C:\Test-Error.ps1:9 char:5
+     Throw "Other complex condition"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Other complex condition:String) [], RuntimeException
    + FullyQualifiedErrorId : Other complex condition

Here, it is line number 9.

Upvotes: 1

Related Questions