Benjamin Hubbard
Benjamin Hubbard

Reputation: 2917

ErrorVariable output not as expected

First, here is my code:

$InputPath = "\\Really\long\path\etc"
Get-ChildItem -Path $InputPath -Recurse -Force -ErrorVariable ErrorPath
$ErrorPath | select TargetObject

The problem I am facing is with the ErrorVariable parameter. Paths that are too long for Get-ChildItem to process are stored there (typically around 250+ characters). When I pipe $ErrorPath to select, the output looks like this:

TargetObject : \\Really\long\path\etc\1

TargetObject : \\Really\long\path\etc\2

TargetObject : \\Really\long\path\etc\3

However, if I run that last line again (either by running selection or by manually typing it in), the output changes to this:

TargetObject
------------
\\Really\long\path\etc\1
\\Really\long\path\etc\2
\\Really\long\path\etc\3

I am at a loss as to how to explain this. I prefer the second output, but I don't know why it is different from the first to the second time. Any ideas?

Upvotes: 1

Views: 490

Answers (2)

Keith Hill
Keith Hill

Reputation: 201622

When there are multiple types of objects in a pipeline the first object type determines the formatting for the rest of the objects. If you ran your commands individually on the command prompt you wouldn't see this. Each line starts a new pipeline. However when you run these commands in a script, the whole script is executed as a pipeline. To work around this use Out-Default e.g.:

$InputPath = "\\Really\long\path\etc"
Get-ChildItem $InputPath -Recurse -Force -ErrorVariable ErrorPath
$ErrorPath | select TargetObject | Out-Default

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

The former output is in list format, the latter in table format. You can enforce one or the other by piping your data into the Format-List or Format-Table cmdlet respectively:

PS C:\> $ErrorPath | select TargetObject | Format-List


TargetObject : \\Really\long\path\etc\1

TargetObject : \\Really\long\path\etc\2

TargetObject : \\Really\long\path\etc\3


PS C:\> $ErrorPath | select TargetObject | Format-Table

TargetObject
------------
\\Really\long\path\etc\1
\\Really\long\path\etc\2
\\Really\long\path\etc\3

Upvotes: 1

Related Questions