Alex McKenzie
Alex McKenzie

Reputation: 912

Populating a variable with -ErrorVariable

I'm using powershell 4.0, and I'm trying to use the -ErrorVariable parameter to populate a variable so that I can check the .count property and see if an error occurred in a previous step. I've tried to use the guide here but I can't seem to get it to work.

I have this portion of the script that calls an xml file

$getError = $null
[xml]$a = Get-Content -ErrorVariable $getError .\test.xml
Write-Host $getError.count

I have the step pull in a malformed xml file, but the valute of $getError remains $null even if the step fails.

Upvotes: 1

Views: 1537

Answers (2)

Mike Shepard
Mike Shepard

Reputation: 18156

In addition to what @mjolinor said, you're passing the value of $getError to the -ErrorVariable parameter. To use -ErrorVariable, you need to pass the name of the variable which doesn't include the $.

$getError = $null
[xml]$a = Get-Content -ErrorVariable getError .\test.xml
Write-Host $getError.count

Upvotes: 8

mjolinor
mjolinor

Reputation: 68243

You're not getting anything because the Get-Content succeeds. What fails is the subsequent cast of the return to [XML], but you can't caputure that with ErrorVariable.
Does this work for you?

$getError = @()
try { [xml]$a = Get-Content  $getError .\test.xml -ErrorAction Stop }
 catch { $getError += $Error[0] }
Write-Host $getError.count

Upvotes: 2

Related Questions